/**
 * @Description: 订单表
 * @author ourslookAdmin
 * @date 2019-04-23 20:47:33
 */
import React, { Fragment } from 'react';
import ReactToPrint from 'react-to-print';
import {
  Alert,
  Avatar,
  BackTop,
  Button,
  Card,
  Cascader,
  Checkbox,
  Col,
  DatePicker,
  Divider,
  Drawer,
  Form,
  Icon,
  Input,
  List,
  notification,
  Popover,
  Radio,
  Row,
  Select,
  Spin,
  Steps,
  Tabs,
  Tag,
  Timeline,
  Tooltip,
  Upload,
} from 'antd';
import { CopyToClipboard } from 'react-copy-to-clipboard';
import Modal from 'drag-modal';
import Zmage from 'react-zmage';
import { formatMessage, FormattedMessage } from 'umi/locale';
import withSizes from 'react-sizes';
import { Link } from 'dva/router';
import moment from 'moment';
import 'antd/dist/antd.css';
import PropTypes from 'prop-types';
import { connect } from 'dva';
import numeral from 'numeral';
import { requestLists, requestPromise } from '@/utils/request';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import BaseForm from '../../../components/ourslook/BaseForm';
import ETable from '../../../components/ourslook/ETable';
import Print from '../../../components/ourslook/Print';
import Ellipsis from '../../../components/ourslook/Ellipsis';
import { getWebPath } from '../../../utils/request';
import uiUtils, { hasPermission, rulesReg } from '../../../utils/uiUtils';
import styles from '../../../utils/ourslook.less';

const FormItem = Form.Item;
const Option = Select.Option;
const RadioGroup = Radio.Group;
const TextArea = Input.TextArea;
const Password = Input.Password;
const CheckboxGroup = Checkbox.Group;
const { RangePicker } = DatePicker;

const getOrderStats = {
  '0': '待付款',
  '1': '待发货',
  '2': '待收货',
  '3': '待评价',
  '4': '交易完成',
  '5': '已取消',
  '100': '已支付（未成团）',
};

const getPayType = {
  '0': '微信',
  '1': '支付宝',
  '2': '银联',
  '3': '钱包支付',
};

const getDeliveryExpressType = {
  A: '整单发货',
  C: '多期发货',
  D: '混合发货',
  B: '多仓发货',
};

const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

//省市区三级数据
let areaAlloptions = JSON.parse(localStorage.getItem('areaAlloptions')) || [];
//所有的快递公司信息
let allExpressInfo = [];

@connect(() => ({}))
@withSizes(({ width }) => ({ width }))
class Order extends React.Component {
  params = {
    page: 1,
    limit: 10,
  };

  formItemLayout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 19 },
  };

  /**
   * https://ant-design.gitee.io/components/table-cn/
   *
   * 需要指定 column 的 width 属性，否则列头和内容可能不对齐。（必须留一列不设宽度或者minWidth以适应弹性布局）
   * 建议指定 scroll.x 为大于表格宽度的固定值或百分比。注意，且非固定列宽度之和不要超过 scroll.x, 一般无table正常展开的宽度
   * 未知长度字段或者字符特别多的字段不要放置在列表
   */
  columns = [
    {
      title: '',
      width: 30,
      align: 'center',
      fixed: 'left',
      render: (value, record, index) => index + 1,
    },
    {
      title: '订单号',
      dataIndex: 'orderNo',
      width: 120,
      align: 'center',
      sorter: false,
      fixed: 'left',
    },
    {
      title: '商品',
      dataIndex: 'orderDetailVos',
      width: 200,
      align: 'center',
      sorter: false,
      fixed: 'left',
      render: (value, record, index) => {
        const tags = record.orderDetailVos;
        const colors = [
          'magenta',
          'red',
          'volcano',
          'orange',
          'gold',
          'lime',
          'green',
          'cyan',
          'blue',
          'geekblue',
          'purple',
        ];
        return (
          <Fragment>
            {tags.map(tag => {
              const color = colors[parseInt(Math.random(0, 1) * colors.length, 0)];
              const product = `${tag.productName}X${tag.productBuyNumber}`;
              return (
                <Tooltip title={product}>
                  <Ellipsis style={{ color }} length={35}>
                    {product}
                  </Ellipsis>
                </Tooltip>
              );
            })}
          </Fragment>
        );
      },
    },
    {
      title: '用户名(下单)',
      dataIndex: 'username',
      width: 120,
      align: 'center',
      sorter: false,
      fixed: 'left',
      render: (value, record, index) => `${value}\n${record.mobile}`,
    },
    {
      title: '支付方式',
      dataIndex: 'payType',
      width: 90,
      align: 'center',
      sorter: false,
      render: (value, record, index) => {
        if (value === 0) {
          return '微信';
        }
        if (value === 1) {
          return '支付宝';
        }
        if (value === 2) {
          return '银联';
        }
        if (value === 3) {
          return '钱包';
        }
        return '--';
      },
    },
    {
      title: '支付金额',
      dataIndex: 'pricePayed',
      width: 120,
      align: 'right',
      sorter: true,
      key: 'price_payed',
      render: (value, record, index) => {
        if (value !== null && value !== undefined) {
          return `￥${numeral(value).format('0,0.00')}`;
        }
        return '-';
      },
    },
    {
      title: '订单总价',
      dataIndex: 'priceFinal',
      width: 120,
      align: 'right',
      sorter: true,
      key: 'price_final',
      render: (value, record, index) => {
        if (value !== null && value !== undefined) {
          return `￥${numeral(value).format('0,0.00')}`;
        }
        return '-';
      },
    },
    {
      title: '下单时间',
      dataIndex: 'timePlaceOrder',
      align: 'center',
      sorter: true,
      key: 'time_place_order',
    },
    {
      title: '订单状态',
      dataIndex: 'statusOrder',
      width: 80,
      align: 'center',
      fixed: 'right',
      render: (value, record, index) =>
        value === 0 ? (
          <Tag style={{ cursor: 'default' }} className={styles.label_success}>
            等待买家付款
          </Tag>
        ) : value === 1 ? (
          <Tag style={{ cursor: 'default' }} className={styles.label_danger}>
            待发货
          </Tag>
        ) : value === 2 ? (
          <Tag style={{ cursor: 'default' }} className={styles.label_primary}>
            待收货
          </Tag>
        ) : value === 3 ? (
          <Tag style={{ cursor: 'default' }} className={styles.label_warning}>
            待评价
          </Tag>
        ) : value === 4 ? (
          <Tag style={{ cursor: 'default' }} className={styles.label_info}>
            交易完成
          </Tag>
        ) : value === 100 ? (
          <Tag style={{ cursor: 'default' }} className={styles.label_coupon}>
            已支付（未成团）
          </Tag>
        ) : value === 101 ? (
          <Tag style={{ cursor: 'default' }} className={styles.label_coupon}>
            已支付首款等待支付尾款
          </Tag>
        ) : (
          <Tag style={{ cursor: 'default' }} className={styles.label_default}>
            已取消
          </Tag>
        ),
    },
    {
      title: '操作',
      dataIndex: '',
      width: 80,
      align: 'center',
      fixed: 'right',
      render: (value, record, index) => {
        const status = value.statusOrder;
        let operateName = ''; //主操作
        let icon = 'edit';
        if (status === 0) {
          operateName = '取消订单';
          icon = 'rollback';
        } else if (status === 1) {
          //发货, 这里目前不提供发货功能，在详情页发货
          icon = 'arrow-right';
          operateName = '';
        } else if (status === 2) {
          operateName = '确认收货';
          icon = 'right-circle';
        }

        return (
          <React.Fragment>
            {/*第一操作*/}
            <a
              hidden={!(hasPermission('order:info') && operateName !== '')}
              onClick={() => {
                this.setStateByTableColume(record, index);
                this.update(value.statusOrder);
              }}
            >
              <Tooltip title={operateName}>
                <Icon style={{ fontSize: '16px', color: '#08c' }} type={icon} />
              </Tooltip>
            </a>
            {/*详情操作*/}
            <Divider
              hidden={!(hasPermission('order:info') && operateName !== '')}
              type="vertical"
            />
            <a
              hidden={!hasPermission('order:info')}
              onClick={() => {
                this.setStateByTableColume(record, index);
                this.view();
              }}
            >
              <Tooltip title={<FormattedMessage id="ours.curd.list.info" defaultMessage="查看" />}>
                <Icon type="info" />
              </Tooltip>
            </a>
          </React.Fragment>
        );
      },
    },
  ];

  constructor(props) {
    super(props);
    this.state = {
      showList: 1, //1:显示列表、2:显示新增
      formList: this.getFormList(),
      selectedRows: [],
      selectedIds: [],
      selectedIndexs: [],
      editModalTitle: null,
      editModalType: null,
      editModel: null,
      editModelConfirmLoading: false,
      //其他属性下面书写
      downloadBtnLoading: false, //下载excel按钮是否加载
      statusOrder: '', //订单状态，用于-tabs和顶部筛选进行数据同步
      batchDeliveryVisible: false, //批量发货-按钮-用来弹出批量发货的对话框
      importOrderVisible: false, //导入第三方订单-按钮-用来弹出第三方订单的对话框
    };
  }

  componentDidMount() {
    this.requestList();
    this.getConstantsList();
  }

  componentWillUnmount() {}

  // 筛选条件
  getFormList = () => [
    {
      type: 'INPUT',
      field: 'username',
      label: '订单号、手机号、姓名(下单人、收货人)',
      placeholder: '订单号、手机号、姓名(下单人、收货人)',
    },
    {
      type: 'SELECT',
      field: 'statusOrder',
      label: '订单状态',
      placeholder: '订单状态',
      initialValue: '',
      list: [{ id: '', name: '请选择订单状态' }, ...uiUtils.getOptionJsonObjToArr(getOrderStats)],
    },
    {
      type: 'SELECT',
      field: 'deliveryExpressType',
      label: '发货方式',
      placeholder: '发货方式',
      initialValue: '',
      list: [
        { id: '', name: '请选择快递发货方式' },
        ...uiUtils.getOptionJsonObjToArr(getDeliveryExpressType),
      ],
    },
    {
      type: 'INPUT',
      field: 'productNames',
      label: '商品名称',
      placeholder: '商品名称',
      initialValue: '',
    },
    {
      type: 'INPUT',
      field: 'shopNote',
      label: '商家备注',
      placeholder: '商家备注',
      initialValue: '',
    },
    {
      type: 'SELECT',
      field: 'orderSource',
      label: '订单来源',
      placeholder: '订单来源',
      initialValue: '',
    },
    {
      type: 'SELECT',
      field: 'payType',
      label: '支付方式',
      placeholder: '支付方式',
      initialValue: '',
      list: [{ id: '', name: '请选择支付方式' }, ...uiUtils.getOptionJsonObjToArr(getPayType)],
    },
    {
      type: 'SELECT',
      field: 'orderPromotionType',
      label: '订单类型',
      placeholder: '订单类型',
      initialValue: '',
    },
    {
      type: 'DATE_RANGE',
      field: 'timePayOrder',
      label: '支付时间',
      placeholder: ['支付时间', ''],
    },
  ];

  /**
   * 根据 formItem field 取值 查找formItem
   * @param formItemField obj的field字段
   * @returns 一个对象
   */
  findFormListItemByField = formItemField =>
    this.state.formList.find((value, index, array) => value.field === formItemField);

  query = fieldParams => {
    //1： 进行查询
    this.params = JSON.parse(JSON.stringify(Object.assign(this.params, fieldParams)));
    this.requestList();

    //2: 进行筛选和tabs状态同步
    this.setState({
      statusOrder: this.params.statusOrder || '',
    });
  };

  getConstantsList = () => {
    requestPromise(`${getWebPath('/api/constants?type=OrderPomotionType,OrderSource,PayType')}`, {
      method: 'GET',
    }).then(res => {
      if (res) {
        //1:设置订单来源
        const orderSources = uiUtils.getOptionJsonObjToArr(res.OrderSource);
        const newOrderSourceArr = [{ id: '', name: '请选择订单来源' }, ...orderSources];
        const { formList: formListNew } = this.state;
        const formItem = this.findFormListItemByField('orderSource');
        formItem.list = newOrderSourceArr;

        //2:设置活动类型
        const orderPromotionTypes = uiUtils.getOptionJsonObjToArr(res.OrderPomotionType);
        const newOrderPromotionTypeArr = [
          { id: '', name: '请商品活动类型' },
          ...orderPromotionTypes,
        ];
        const formItem2 = this.findFormListItemByField('orderPromotionType');
        formItem2.list = newOrderPromotionTypeArr;

        //3:设置支付方式
        const payTypes = uiUtils.getOptionJsonObjToArr(res.PayType);
        const payTypeArr = [{ id: '', name: '请选择支付方式' }, ...payTypes];
        const formItem3 = this.findFormListItemByField('payType');
        formItem3.list = payTypeArr;

        this.setState({
          formList: formListNew,
        });
      }
    });
  };

  add = () => {
    this.setState({
      editModalType: 'add',
      editModalTitle: formatMessage({ id: 'ours.curd.list.create' }), //创建
      editModel: {},
      showList: 2,
    });
  };

  view = () => {
    const { selectedRows, selectedIds, selectedIndexs } = this.state;
    if (!selectedRows) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-please' }));
      return;
    }
    if (selectedRows.length > 1) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-one-please' }));
      return;
    }
    const orderInfo = selectedRows[0];
    //设置订单详情默认值
    if (orderInfo.orderDetailVos === null || orderInfo.orderDetailVos === undefined) {
      orderInfo.orderDetailVos = [];
    }
    this.setState({
      editModalType: 'view',
      editModalTitle: `查看订单`,
      editModel: orderInfo,
      showList: 2,
    });
    this.getInfo(orderInfo.id);
  };

  getInfo = id => {
    this.setState({
      editModelConfirmLoading: true,
    });
    requestPromise(getWebPath(`/order/info/${id}`), {
      method: 'GET',
    }).then(res => {
      this.setState({
        editModelConfirmLoading: false,
      });
      if (res && res.code === 0) {
        //设置订单详情默认值
        const orderInfo = res.order;
        if (orderInfo.orderDetailVos === null || orderInfo.orderDetailVos === undefined) {
          orderInfo.orderDetailVos = [];
        }

        // 增加属性 图书专发是完成
        orderInfo.bookSpecializedSucess =
          orderInfo.orderAddress &&
          orderInfo.orderAddress.expressDeliveryMethod !== null &&
          orderInfo.orderAddress.expressDeliveryMethod !== undefined;

        this.setState({
          editModel: orderInfo,
        });
      }
    });
  };

  setStateByTableColume = (record, index) => {
    this.state = {
      ...this.state,
      selectedRows: [record],
      selectedIds: [record.id],
      selectedIndexs: [index],
    };
  };

  deleteOrders = () => {
    //这里处理，发布、取消发布、删除、禁用等状态操作; 参数status由调用放传入
    const { selectedRows, selectedIds, selectedIndexs } = this.state;
    const ids = [];
    for (let i = 0; i < selectedRows.length; i += 1) {
      ids.push(selectedRows[i].id);
    }

    const msgIds = 'ours.curd.show-alert.confirm-delete';
    uiUtils.showConfirm(formatMessage({ id: msgIds }), () => {
      this.setState({
        loading: true,
      });
      requestPromise(`${getWebPath()}order/delete`, {
        method: 'POST',
        body: ids,
      }).then(res => {
        this.setState({
          loading: false,
        });
        if (res && res.code === 0) {
          uiUtils.showMessage(
            formatMessage({ id: 'ours.curd.show-alert.operate-success' }),
            'success'
          );
          this.requestList();
        }
      });
    });
  };

  update = status => {
    let operateName = ''; //主操作
    let url = '';
    if (status === 0) {
      operateName = '取消订单';
      url = '/order/cancel';
    } else if (status === 1) {
      operateName = '发货';
      return;
    } else if (status === 2) {
      operateName = '确认收货, 操作不可逆转，请确定客户真实收到货品';
      url = '/order/confirm';
    } else {
      return;
    }
    const orderId = this.state.selectedIds[0];

    uiUtils.showConfirm(`确定${operateName}`, () => {
      this.setState({ loading: true });
      requestPromise(getWebPath() + url, {
        method: 'POST',
        contentType: 'application/x-www-form-urlencoded',
        body: { orderId },
      }).then(res => {
        this.setState({ loading: false });
        if (res && res.code === 0) {
          uiUtils.showMessage(res.info, 'success');
          this.requestList();
        }
      });
    });
  };

  /**
   * 订单状态的tabs被选择
   * @param statusOrder
   */
  tabsOnSelect = statusOrder => {
    //1：修改搜索栏的取值：
    const formItem1 = this.findFormListItemByField('statusOrder');
    formItem1.initialValue = statusOrder;

    const { formList: formListNew } = this.state;
    this.setState({
      formList: formListNew,
      statusOrder,
    });

    //2：进行搜索
    this.params.statusOrder = statusOrder;

    this.requestList();
  };

  /**
   * 下载数据、下载批量发货数据、下载当天发货数据
   * @param isExcel
   * @param deliveryMonth "todays"就是当天发货数据
   */
  exportsAllToExcel = (isExcel, deliveryMonth) => {
    let params = JSON.parse(JSON.stringify(this.params));

    //如果是是导出待发货信息，这里简单处理一下, 全都是待发货数据
    if (deliveryMonth !== undefined && deliveryMonth !== null && deliveryMonth !== '') {
      params = JSON.parse(JSON.stringify(Object.assign(params, { statusOrder: 1 })));
    }

    //删除属性
    //delete params.page;
    //delete params.limit;
    //这里默认导出，excel 07版本以上已经支持100万了，这里写上 10万把。 太多 excel也打不开了
    params.limit = 100000;

    const data = `searchParams=${encodeURIComponent(JSON.stringify(params))}&isCvs=${
      isExcel ? 'false' : 'true'
    }&deliveryMonth=${deliveryMonth}`;
    window.location.href = `${getWebPath()}order/exportsExcelAll?${data}`;
  };

  exportsOrderToExcel = (isExcel, platFormType) => {
    const data = `isCvs=${isExcel ? 'false' : 'true'}&platFormType=${platFormType}`;

    window.location.href = `${getWebPath()}order/exportsOrderToExcel?${data}`;
  };

  updateShopNote = () => {
    const { selectedRows } = this.state;
    const ids = [];
    for (let i = 0; i < selectedRows.length; i += 1) {
      ids.push(selectedRows[i].id);
    }
    let data = {
      modelIds: ids.join(','),
      shopNoteOld: this.state.orderShopNoteModel.shopNoteOld,
      shopNote: this.state.orderShopNoteModel.shopNote,
    };

    const params = JSON.parse(JSON.stringify(this.params));
    //删除属性
    delete params.page;
    delete params.limit;
    data = { ...data, ...params };

    this.updateOrderShopNoteForm.props.form.validateFieldsAndScroll((err, values) => {
      // eslint-disable-next-line no-prototype-builtins
      if (!err) {
        //这里提示一下,确认是否修改
        const msgTip =
          ids.length > 0
            ? `确认替换/修改选中的${ids.length}条订单商家备注吗？`
            : '确定替换/修改查询条件内所有订单商家备注吗';
        uiUtils.showConfirm(msgTip, () => {
          this.setState({
            orderShopNoteLoading: true,
          });
          requestPromise(`${getWebPath()}/order/updateBatchShopNote`, {
            method: 'POST',
            contentType: 'application/x-www-form-urlencoded',
            body: data,
          }).then(res => {
            this.setState({
              orderShopNoteLoading: false,
            });
            if (res && res.code === 0) {
              this.setState({
                orderShopNoteLoading: false,
                orderShopNoteVisible: false,
              });
              uiUtils.showMessage(
                formatMessage({ id: 'ours.curd.show-alert.operate-success' }),
                'success'
              );
              this.setState({
                showList: 1,
              });
              this.requestList();
            }
          });
        });
      }
    });
  };

  //========其他所有的处理方法，请在按照约定进行处理==========

  /**
   * 表格 筛选和排序 回调
   */
  filtersSorterChange = tableParams => {
    this.params = JSON.parse(JSON.stringify(Object.assign(this.params, tableParams)));
    this.requestList();
  };

  requestList = () => {
    requestLists(this, `${getWebPath()}order/listVo`, this.params);
  };

  vShow = showListNum => ({ display: this.state.showList === showListNum ? 'block' : 'none' });

  render() {
    const firstButtonStyle = {
      style: {
        // marginLeft: 10,
        marginTop: 10,
      },
      //disabled: this.state.selectedIndexs.length <= 0,
    };
    const style = {
      style: {
        marginLeft: 10,
        marginTop: 10,
      },
      //disabled: this.state.selectedIndexs.length <= 0,
    };

    /* eslint-disable react/jsx-no-bind */
    return (
      <PageHeaderWrapper title="">
        <Card
          bordered={false}
          //style={{...this.vShow(1)}}
          className={styles.oursCard}
          bodyStyle={{ padding: '20px' }}
        >
          <BaseForm
            formList={this.state.formList}
            loading={this.state.loading}
            filterSubmit={this.query}
          />

          <Fragment>
            <Button
              type="primary"
              icon="download"
              {...firstButtonStyle}
              loading={this.state.downloadBtnLoading}
              onClick={() => {
                this.setState({
                  downloadBtnLoading: true,
                });
                this.exportsAllToExcel(true);
                //这里延迟5s关闭loading
                setTimeout(() => {
                  this.setState({
                    downloadBtnLoading: false,
                  });
                }, 1000 * 5);
              }}
              hidden={!hasPermission('order:list')}
            >
              <FormattedMessage id="ours.curd.list.export" defaultMessage="导出" />
            </Button>
            <Button
              type="primary"
              icon="upload"
              {...style}
              onClick={() => {
                this.setState({
                  batchDeliveryVisible: true,
                });
              }}
              hidden={!hasPermission('order:list')}
            >
              批量发货
            </Button>
            <Button
              type="primary"
              icon="upload"
              {...style}
              onClick={() => {
                this.setState({
                  importOrderVisible: true,
                });
              }}
            >
              导入第三方订单
            </Button>
            <Button
              type="primary"
              icon="highlight"
              {...style}
              onClick={() => {
                //这里如果不选择行，就批量修改所有的
                this.setState({
                  orderShopNoteVisible: true,
                  orderShopNoteModel: {
                    shopNoteOld: '',
                    shopNote: '',
                  },
                });
              }}
            >
              批量修改
            </Button>
            <Button
              type="danger"
              icon="delete"
              {...style}
              onClick={() => {
                this.deleteOrders();
              }}
              hidden={!hasPermission('order:update')}
            >
              <FormattedMessage id="ours.curd.list.delete" defaultMessage="禁用" />
            </Button>
          </Fragment>

          <div className="content-wrap">
            <Tabs
              onChange={key => {
                this.tabsOnSelect(key);
              }}
              style={{ marginTop: '20px' }}
              activeKey={this.state.statusOrder || ''}
              type="card"
            >
              <Tabs.TabPane tab="全部" key="" />
              <Tabs.TabPane tab="待付款" key="0" />
              <Tabs.TabPane tab="待发货" key="1" />
              <Tabs.TabPane tab="待收货" key="2" />
              <Tabs.TabPane tab="待评价" key="3" />
              <Tabs.TabPane tab="交易完成" key="4" />
              <Tabs.TabPane tab="已取消" key="5" />
              <Tabs.TabPane tab="已支付（未成团）" key="100" />
            </Tabs>
            <ETable
              onSelectRow={uiUtils.onSelectRow.bind(this)}
              primaryKey="id"
              selectedRows={this.state.selectedRows}
              selectedIds={this.state.selectedIds}
              selectedIndexs={this.state.selectedIndexs}
              onChange={this.filtersSorterChange}
              columns={this.columns}
              dataSource={this.state.list}
              pagination={this.state.pagination}
              loading={this.state.loading}
              scroll={{ x: 1250 }}
              //rowSelection={{}}
            />
          </div>
        </Card>

        <BackTop />

        {/*这里是导入第三方订单*/}
        <ImportOrderForm
          onOk={() => {
            this.setState({ importOrderVisible: false });
            this.importOrderForm.setState({
              uploadResultDisplay: false,
              uploadResultInfo: '',
              fileList: [],
              platForm: '',
            });
          }}
          onCancel={() => {
            this.setState({ importOrderVisible: false });
          }}
          demoloading={platFormType => {
            this.exportsOrderToExcel(true, platFormType);
          }}
          refreshOrder={() => {
            this.requestList();
          }}
          visible={this.state.importOrderVisible}
          wrappedComponentRef={inst => {
            this.importOrderForm = inst;
          }}
        />

        {/*这里是批量发货*/}
        <BatchDeliveryForm
          onCancel={() => {
            this.setState({ batchDeliveryVisible: false });
          }}
          onDownloading={monthStr => {
            this.exportsAllToExcel(true, monthStr);
          }}
          refreshOrder={() => {
            this.requestList();
          }}
          visible={this.state.batchDeliveryVisible}
        />

        {//返回null,这里对不用的组件进行销毁
        this.state.showList === 1 ? null : (
          <Drawer
            width={this.props.width / 2.0 < 750 ? 750 : this.props.width / 2.0}
            placement="right"
            closable
            onClose={() => {
              this.setState({
                showList: 1,
              });
            }}
            destroyOnClose
            title={this.state.editModalTitle}
            visible={this.state.showList === 2}
          >
            <EditForm
              type={this.state.editModalType}
              model={this.state.editModel}
              infoLoading={this.state.editModelConfirmLoading}
              wrappedComponentRef={inst => {
                this.editForm = inst;
              }}
            />
          </Drawer>
        )}
        <UpdateOrderShopNoteForm
          onOk={() => {
            this.updateShopNote();
          }}
          onCancel={() => {
            this.setState({ orderShopNoteVisible: false });
          }}
          orderShopNoteModel={this.state.orderShopNoteModel}
          visible={this.state.orderShopNoteVisible}
          orderShopNoteLoading={this.state.orderShopNoteLoading}
          wrappedComponentRef={inst => {
            this.updateOrderShopNoteForm = inst;
          }}
        />
      </PageHeaderWrapper>
    );
  }
}

export default Order;

class UpdateOrderShopNoteForm extends React.Component {
  static propTypes = {
    orderShopNoteModel: PropTypes.object,
    visible: PropTypes.bool,
    orderShopNoteLoading: PropTypes.bool,
    onCancel: PropTypes.func,
    onOk: PropTypes.func,
  };

  static defaultProps = {
    orderShopNoteModel: null,
    visible: false,
    orderShopNoteLoading: false,
    onCancel: () => {},
    onOk: () => {},
  };

  constructor(props) {
    super(props);
    this.state = {};
  }

  render() {
    const orderShopNoteLoading = this.props.orderShopNoteLoading;
    const visible = this.props.visible;
    const onCancel = this.props.onCancel;
    const onOk = this.props.onOk;
    const orderShopNoteModel = this.props.orderShopNoteModel || {};

    const {
      form,
      form: { getFieldDecorator, getFieldValue, setFieldsValue },
    } = this.props;
    const formItemLayout = {
      labelCol: { span: 5 },
      wrapperCol: { span: 18 }, //5+19=24,少壹個柵格
    };
    const colSpanLayout = { md: 24, sm: 24 }; //每壹col跨?列
    const rowGutterPxLayout = { md: 24, sm: 24 }; //col之間的間隔?px
    //校驗文檔：https://ant.design/components/form-cn/#%E6%A0%A1%E9%AA%8C%E8%A7%84%E5%88%99
    return (
      <Modal
        title="批量修改"
        visible={visible}
        onCancel={onCancel}
        onOk={onOk}
        destroyOnClose
        closable
        width={600}
        saveDistance={0}
        confirmLoading={orderShopNoteLoading}
      >
        <Tabs style={{ marginTop: '20px' }} defaultActiveKey="0" tabPosition="left" type="line">
          <Tabs.TabPane tab="批量更新商家备注" key="0">
            <Form layout="horizontal">
              <Row gutter={{ ...rowGutterPxLayout }}>
                <Col {...colSpanLayout}>
                  <FormItem label="商家备注" {...formItemLayout}>
                    {getFieldDecorator('shopNote', {
                      initialValue: orderShopNoteModel.shopNote,
                      rules: [
                        {
                          required: true,
                          message: '商家备注必填',
                        },
                      ],
                    })(
                      <TextArea
                        type="text"
                        autocomplete="off"
                        placeholder="商家备注"
                        onChange={e => {
                          orderShopNoteModel.shopNote = e.target.value;
                        }}
                      />
                    )}
                  </FormItem>
                </Col>
              </Row>
            </Form>
          </Tabs.TabPane>
          <Tabs.TabPane tab="批量替换商家备注" key="1">
            <Form layout="horizontal">
              <Row gutter={{ ...rowGutterPxLayout }}>
                <Col {...colSpanLayout}>
                  <FormItem label="原始内容" {...formItemLayout}>
                    {getFieldDecorator('shopNoteOld', {
                      initialValue: orderShopNoteModel.shopNoteOld,
                      rules: [
                        {
                          required: false,
                          message: '将要替换的内容',
                        },
                      ],
                    })(
                      <Input
                        type="text"
                        autocomplete="off"
                        placeholder="将要替换的内容"
                        onChange={e => {
                          orderShopNoteModel.shopNoteOld = e.target.value;
                        }}
                      />
                    )}
                  </FormItem>
                </Col>
                <Col {...colSpanLayout}>
                  <FormItem label="新的内容" {...formItemLayout}>
                    {getFieldDecorator('shopNote', {
                      initialValue: orderShopNoteModel.shopNote,
                      rules: [
                        {
                          required: true,
                          message: '替换后的内容必填',
                        },
                      ],
                    })(
                      <Input
                        type="text"
                        autocomplete="off"
                        placeholder="替换后的内容"
                        onChange={e => {
                          orderShopNoteModel.shopNote = e.target.value;
                        }}
                      />
                    )}
                  </FormItem>
                </Col>
              </Row>
            </Form>
          </Tabs.TabPane>
        </Tabs>
      </Modal>
    );
  }
}

/* eslint-disable no-class-assign */
//無更多的綁定， 請用 @Form.create() 註解替換
UpdateOrderShopNoteForm = Form.create({})(UpdateOrderShopNoteForm);

/**
 * 第三方订单的表单
 */
class ImportOrderForm extends React.Component {
  static propTypes = {
    visible: PropTypes.bool, //第三方订单modal是否显示
    onCancel: PropTypes.func, //第三方订单modal关闭事件
    demoloading: PropTypes.func, //第三方订单modal关闭事件
    refreshOrder: PropTypes.func, //刷新订单列表
  };

  static defaultProps = {
    visible: false,
    onCancel: () => {},
    demoloading: platFormType => {},
    refreshOrder: null,
  };

  constructor(props) {
    super(props);
    this.getPlatFormList();
    this.state = {
      demoloadingLoading: false, //下载按钮是否loading中
      uploadLoading: false, //导入loading框框
      uploadResultDisplay: false, //导入结果是否显示
      uploadResultInfo: '', //导入结果信息
      fileList: [],
      platFormList: [],
      platForm: '',
    };
  }

  //获取平台数据
  getPlatFormList = file => {
    requestPromise(`${getWebPath('/orderimportplatform/list')}`, {
      method: 'POST',
    }).then(res => {
      if (res && res.code === 0) {
        const platForms = res.page.list || [];
        const newPlatForms = [
          { id: '', name: '请选择平台' },
          ...platForms.map(e => ({ id: e.id, name: e.platformName })),
        ];
        this.setState({
          platFormList: newPlatForms,
        });
      }
    });
  };

  handleUploadOnRemove = file => {
    this.setState({
      fileList: [],
    });
  };

  handleUploadOnChange = info => {
    // 状态有：uploading done error removed
    if (info.file.status === 'done') {
      //这个Upload组件比较特殊，这里在OnChange方法手工设置value,不做延迟，就设置不了被覆盖了。
      this.setState({
        fileList: info.fileList,
      });
      const response = info.fileList[0].response;
      if (response) {
        this.setState({
          uploadLoading: false,
        });
        if (response.code === 0) {
          uiUtils.showMessage(`${info.file.name} 第三方订单导入完毕,请下载结果excel`, 'success');
          //这里可以下载批量发货的情况
          this.setState({
            uploadResultDisplay: true,
            uploadResultInfo: response.result,
          });
          if (this.props.refreshOrder) {
            this.props.refreshOrder();
          }
        } else {
          this.setState({
            uploadResultDisplay: true,
            uploadResultInfo: response.msg,
          });
        }
      }
    } else if (info.file.status === 'error') {
      uiUtils.showMessage(`${info.file.name} 文件上传失败.`, 'error');
      this.setState({
        uploadLoading: false,
      });
    } else if (info.file.status === 'uploading') {
      this.setState({
        uploadLoading: true,
      });
    }
  };

  render() {
    const visible = this.props.visible;
    const onCancel = this.props.onCancel;
    const demoloadingLoading = this.state.demoloadingLoading;
    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">上传</div>
      </div>
    );
    const uploadProps = {
      action: `${getWebPath('/order/importOrderFromExcel')}`,
      name: 'myfile',
      data: { moduleName: 'order', isImage: false, orderObjId: this.state.platForm },
      withCredentials: true,
      headers: {
        authorization: 'authorization-text',
      },
      onChange: this.handleUploadOnChange,
      onRemove: this.handleUploadOnRemove,
      multiple: false,
      accept:
        '.csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel,' +
        '',
    };
    const {
      form,
      form: { getFieldDecorator, getFieldValue, setFieldsValue },
    } = this.props;
    const formItemLayout = {
      labelCol: { span: 5 },
      wrapperCol: { span: 18 }, //5+19=24,少一个栅格
    };
    const colSpanLayout = { md: 24, sm: 24 }; //每一col跨?列
    const rowGutterPxLayout = { md: 24, sm: 24 }; //col之间的间隔?px
    //校验文档：https://ant.design/components/form-cn/#%E6%A0%A1%E9%AA%8C%E8%A7%84%E5%88%99
    return (
      <Modal
        title="第三方订单"
        visible={visible}
        onCancel={onCancel}
        destroyOnClose
        closable
        okButtonProps={{ icon: 'down-circle', htmlType: 'submit', disabled: true, hidden: true }}
        cancelButtonProps={{ loading: this.state.uploadLoading, text: '取消', type: 'default' }}
        width={600}
        saveDistance={0}
      >
        <Form layout="horizontal">
          <Row gutter={{ ...rowGutterPxLayout }}>
            <Col {...colSpanLayout}>
              <FormItem
                label="样例下载"
                colon={false}
                {...{
                  labelCol: { span: 5 },
                  wrapperCol: { span: 10 }, //5+19=24,少一个栅格
                }}
              >
                <Button
                  size="small"
                  loading={demoloadingLoading}
                  onClick={() => {
                    this.props.demoloading('1');
                    this.setState({
                      demoloadingLoading: true,
                    });
                    //这里延迟5s关闭loading
                    setTimeout(() => {
                      this.setState({
                        demoloadingLoading: false,
                      });
                    }, 1000 * 5);
                  }}
                >
                  样例下载
                </Button>
              </FormItem>
            </Col>
            <Col {...colSpanLayout}>
              <FormItem
                label="平台"
                colon={false}
                {...{
                  labelCol: { span: 5 },
                  wrapperCol: { span: 10 }, //5+19=24,少一个栅格
                }}
              >
                {getFieldDecorator('platForm', {
                  initialValue: this.state.platForm,
                  rules: [
                    {
                      required: true,
                      message: '平台必选',
                    },
                  ],
                })(
                  <Select
                    style={{ width: '100%' }}
                    placeholder="请选择平台"
                    onChange={value => {
                      this.setState({
                        platForm: value,
                      });
                    }}
                  >
                    {uiUtils.getOptionList(this.state.platFormList)}
                  </Select>
                )}
              </FormItem>
            </Col>
            {this.state.platForm !== '' && (
              <Col {...colSpanLayout}>
                <FormItem
                  label="文件"
                  extra={
                    <Fragment>
                      最大支持 10000 条记录（支持 xls、xlsx，文件大小请控制在 5MB 以内;
                      <span style={{ display: 'block', color: 'blue' }}>
                        1:
                        按照模板要求填写信息，相关数据不要写成E+22科学计数法，日期请使用文本格式；
                      </span>
                      <span style={{ display: 'block', color: 'blue' }}>
                        2: 点击红色部分下载【查看失败原因】，对症修改，成功率更高。；
                      </span>
                      <span style={{ display: 'block', color: 'blue' }}>
                        3: 简单一点，全选excel，设置所有单元格格式，纯文本；
                      </span>
                      <span style={{ display: 'block', color: 'blue' }}>
                        4: 多种杂志，杂志名称、购买数量用逗号分开；
                      </span>
                    </Fragment>
                  }
                  {...formItemLayout}
                >
                  {getFieldDecorator('file', {
                    initialValue: '',
                    rules: [
                      {
                        required: true,
                        message: '文件必填',
                      },
                    ],
                  })(
                    <Spin spinning={this.state.uploadLoading} delay={0}>
                      <Upload
                        listType="picture-card"
                        showUploadList={{ showPreviewIcon: false, showRemoveIcon: true }}
                        {...uploadProps}
                      >
                        {this.state.fileList && this.state.fileList.length >= 1
                          ? null
                          : uploadButton}
                      </Upload>
                    </Spin>
                  )}
                  <div
                    style={{
                      display: this.state.uploadResultDisplay ? 'block' : 'none',
                      lineHeight: '16px',
                      color: 'red',
                    }}
                  >
                    <span dangerouslySetInnerHTML={{ __html: this.state.uploadResultInfo }} />
                  </div>
                </FormItem>
              </Col>
            )}
          </Row>
        </Form>
      </Modal>
    );
  }
}

/* eslint-disable no-class-assign */
//无更多的绑定， 请用 @Form.create() 注解替换
ImportOrderForm = Form.create({})(ImportOrderForm);

/**
 * 批量发货的表单
 */
class BatchDeliveryForm extends React.Component {
  static propTypes = {
    visible: PropTypes.bool, //批量发货modal是否显示
    onCancel: PropTypes.func, //批量发货modal关闭事件
    onDownloading: PropTypes.func, //批量发货modal关闭事件
    refreshOrder: PropTypes.func, //刷新订单列表
  };

  static defaultProps = {
    visible: false,
    onCancel: () => {},
    onDownloading: month => {
      //月份形如：2019-05
    },
    refreshOrder: null,
  };

  constructor(props) {
    super(props);
    this.state = {
      onDownloadingLoading: false, //下载按钮是否loading中
      uploadLoading: false, //导入loading框框
      uploadResultDisplay: false, //导入结果是否显示
      uploadResultInfo: '', //导入结果信息
      fileList: [],
    };
  }

  handleUploadOnRemove = file => {
    this.setState({
      fileList: [],
    });
  };

  handleUploadOnChange = info => {
    // 状态有：uploading done error removed
    if (info.file.status === 'done') {
      //这个Upload组件比较特殊，这里在OnChange方法手工设置value,不做延迟，就设置不了被覆盖了。
      this.setState({
        fileList: info.fileList,
      });
      const response = info.fileList[0].response;
      if (response) {
        this.setState({
          uploadLoading: false,
        });
        if (response.code === 0) {
          uiUtils.showMessage(
            `${info.file.name} 批量发货处理完毕,请下载发货结果excel、或者到订单详情查看`,
            'success'
          );
          // setTimeout(() => {
          //   // console.log(response.object);
          //   this.props.form.setFieldsValue({
          //     image: response.object,
          //   });
          // }, 500);
          //这里可以下载批量发货的情况
          this.setState({
            uploadResultDisplay: true,
            uploadResultInfo: response.result,
          });
          if (this.props.refreshOrder) {
            this.props.refreshOrder();
          }
        } else {
          //uiUtils.showAlert(response.msg, 'error');
          this.setState({
            uploadResultDisplay: true,
            uploadResultInfo: response.msg,
          });
        }
      }
    } else if (info.file.status === 'error') {
      uiUtils.showMessage(`${info.file.name} 文件上传失败.`, 'error');
      this.setState({
        uploadLoading: false,
      });
    } else if (info.file.status === 'uploading') {
      this.setState({
        uploadLoading: true,
      });
    }
  };

  render() {
    const visible = this.props.visible;
    const onCancel = this.props.onCancel;
    const onDownloadingLoading = this.state.onDownloadingLoading;
    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">上传</div>
      </div>
    );
    const uploadProps = {
      // name: 'file',
      // action: '//jsonplaceholder.typicode.com/posts/',
      action: `${getWebPath('/order/uploadExcelForDelivery')}`,
      name: 'myfile',
      data: { moduleName: 'order', isImage: false },
      withCredentials: true,
      headers: {
        authorization: 'authorization-text',
      },
      onChange: this.handleUploadOnChange,
      onRemove: this.handleUploadOnRemove,
      //defaultFileList: [],
      multiple: false,
      accept:
        //'.jpg, .jpeg, .png, .bmp, ' + //image/*
        '.csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel,' + //excel
        //'.doc,.docx,,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document, ' + //word
        //'.pdf, .txt, .xml',
        '',
    };
    const {
      form,
      form: { getFieldDecorator, getFieldValue, setFieldsValue },
    } = this.props;
    const formItemLayout = {
      labelCol: { span: 5 },
      wrapperCol: { span: 18 }, //5+19=24,少一个栅格
    };
    const colSpanLayout = { md: 24, sm: 24 }; //每一col跨?列
    const rowGutterPxLayout = { md: 24, sm: 24 }; //col之间的间隔?px
    //校验文档：https://ant.design/components/form-cn/#%E6%A0%A1%E9%AA%8C%E8%A7%84%E5%88%99
    return (
      <Modal
        title="批量发货"
        visible={visible}
        onCancel={onCancel}
        closable
        okButtonProps={{ icon: 'down-circle', htmlType: 'submit', disabled: true, hidden: true }}
        cancelButtonProps={{ loading: this.state.uploadLoading, text: '取消', type: 'default' }}
        width={600}
        saveDistance={0}
      >
        <Form layout="horizontal">
          <Row gutter={{ ...rowGutterPxLayout }}>
            <Col {...colSpanLayout}>
              <Spin spinning={this.state.uploadLoading}>
                <FormItem
                  label="文件"
                  extra={
                    <Fragment>
                      最大支持 10000 条记录（支持 xls、xlsx，文件大小请控制在 5MB 以内;
                      <span style={{ display: 'block', color: 'blue' }}>
                        1:
                        按照模板要求填写信息，相关数据不要写成E+22科学计数法，日期请使用文本格式；
                      </span>
                      <span style={{ display: 'block', color: 'blue' }}>
                        2: 点击红色部分下载【查看失败原因】，对症修改，成功率更高。；
                      </span>
                      <span style={{ display: 'block', color: 'blue' }}>
                        3: 简单一点，全选excel，设置所有单元格格式，纯文本；
                      </span>
                    </Fragment>
                  }
                  {...formItemLayout}
                >
                  {getFieldDecorator('file', {
                    initialValue: '',
                    rules: [
                      {
                        required: true,
                        message: '文件必填',
                      },
                    ],
                  })(
                    <Upload
                      listType="picture-card"
                      showUploadList={{ showPreviewIcon: false, showRemoveIcon: true }}
                      {...uploadProps}
                    >
                      {this.state.fileList && this.state.fileList.length >= 1 ? null : uploadButton}
                    </Upload>
                  )}
                  <div
                    style={{
                      display: this.state.uploadResultDisplay ? 'block' : 'none',
                      lineHeight: '16px',
                      color: 'red',
                    }}
                  >
                    <span dangerouslySetInnerHTML={{ __html: this.state.uploadResultInfo }} />
                  </div>
                </FormItem>
              </Spin>
            </Col>
            <Col {...colSpanLayout}>
              <FormItem
                label="发货数据"
                extra="如发现导出数据不全，请清空列表所有查询条件"
                colon={false}
                {...{
                  labelCol: { span: 5 },
                  wrapperCol: { span: 10 }, //5+19=24,少一个栅格
                }}
              >
                {getFieldDecorator('month', {
                  initialValue: [moment(), moment()],
                  rules: [
                    {
                      required: false,
                      message: '月份',
                    },
                  ],
                })(
                  <DatePicker.RangePicker
                    style={{ width: '100%' }}
                    format="YYYY-MM"
                    mode={['month', 'month']}
                    onChange={value => {
                      this.props.form.setFieldsValue({
                        month: value,
                      });
                    }}
                    onPanelChange={(value, mode) => {
                      this.props.form.setFieldsValue({
                        month: value,
                      });
                    }}
                    placeholder="指定月份"
                  />
                )}
                <Button
                  size="small"
                  icon="download"
                  loading={onDownloadingLoading}
                  onClick={() => {
                    const month = this.props.form.getFieldsValue().month;
                    const monthStr = `${month[0].format('YYYY-MM')}~${month[1].format('YYYY-MM')}`;
                    this.props.onDownloading(monthStr);
                    this.setState({
                      onDownloadingLoading: true,
                    });
                    //这里延迟5s关闭loading
                    setTimeout(() => {
                      this.setState({
                        onDownloadingLoading: false,
                      });
                    }, 1000 * 5);
                  }}
                >
                  下载批量发货数据[指定月份多期]
                </Button>
                <Button
                  size="small"
                  icon="download"
                  loading={onDownloadingLoading}
                  onClick={() => {
                    this.props.onDownloading('todays');
                    this.setState({
                      onDownloadingLoading: true,
                    });
                    //这里延迟5s关闭loading
                    setTimeout(() => {
                      this.setState({
                        onDownloadingLoading: false,
                      });
                    }, 1000 * 5);
                  }}
                >
                  下载批量发货数据[全部时间普通商品]
                </Button>
              </FormItem>
            </Col>
          </Row>
        </Form>
      </Modal>
    );
  }
}

/* eslint-disable no-class-assign */
//无更多的绑定， 请用 @Form.create() 注解替换
BatchDeliveryForm = Form.create({})(BatchDeliveryForm);

class ControlledRangePicker extends React.Component {
  static propTypes = {
    visible: PropTypes.bool,
    // onOk: PropTypes.func,
    onPanelChange: PropTypes.func,
    // initValDelivery: PropTypes.obj,
  };

  static defaultProps = {
    visible: false,
    onPanelChange: () => {},
    // initValDelivery: [],
  };

  constructor(props) {
    super(props);
    this.state = {
      mode: ['month', 'month'],
      value: [],
      isOpen: true,
    };
  }

  handlePanelChange = (value, mode) => {
    this.setState({
      value,
      mode: [mode[0] === 'date' ? 'month' : mode[0], mode[1] === 'date' ? 'month' : mode[1]],
    });
  };

  handleChange = value => {
    // console.log("handleChange");
    // console.log(value);
    this.setState({ value });
  };

  render() {
    const { value, mode, isOpen } = this.state;
    const onPanelChange = this.props.onPanelChange;
    const initValDelivery = this.props.initValDelivery;
    return (
      <RangePicker
        placeholder={['开始月份', '结束月份']}
        format="YYYY-MM"
        value={value}
        mode={mode}
        onOpenChange={status => {
          // console.log(status);
        }}
        onChange={this.handleChange}
        onPanelChange={(value1, mode1) => {
          this.handlePanelChange(value1, mode1);
          onPanelChange(value1);
        }}
      />
    );
  }
}

/**
 *  新增、编辑、复制、查看的Form
 */

/* eslint react/no-multi-comp:0 */
class EditForm extends React.Component {
  static propTypes = {
    type: PropTypes.string, //form类型，可选值：add（增加）、update（修改）、copy（复制）、view（查看）、
    model: PropTypes.object, //数据模型model，对应后台的model
    infoLoading: PropTypes.bool, //订单详情数据是否在加载中
  };

  static defaultProps = {
    type: '', //表单布局数组
    model: null,
    infoLoading: false,
  };

  orderDeliverysColumns = [
    {
      title: '期数',
      dataIndex: 'sort',
      width: 45,
      align: 'center',
      fixed: 'left',
      render: (value, record, index) => index + 1,
    },
    {
      title: '所属月份',
      dataIndex: 'belongMonth',
      width: 85,
      align: 'center',
      sorter: false,
      render: (value, record, index) =>
        value !== null && value !== undefined && value.length > 6 ? value.substring(0, 7) : '',
    },
    {
      title: '预计发货',
      dataIndex: 'estimatedDeliveryTime',
      width: 105,
      align: 'center',
      sorter: false,
      render: value => `${value}`,
    },
    {
      title: '实际发货',
      dataIndex: 'actualDeliveryTime',
      width: 105,
      align: 'center',
    },
    {
      title: '物流|单号',
      dataIndex: 'expressNumber',
      width: 120,
      align: 'center',
      sorter: false,
      render: (value, record, index) => {
        if (value !== null && value !== undefined) {
          return `${record.expressName}\n${record.expressNumber}`;
        }
        return '-';
      },
    },
    {
      title: '状态',
      dataIndex: 'expressDeliveryMethod',
      align: 'center',
      sorter: false,
      render: (value, record, index) => {
        if (value !== null && value !== undefined) {
          return record.expressDeliveryMethod === 1 ? '无需物流' : '有物流';
        }
        return '-';
      },
    },
  ];

  constructor(props) {
    super(props);
    //设置默认值
    if (this.props.model === null || this.props.model === undefined) {
      this.props.model = { orderDetailVos: [] };
    }
    this.state = {
      type: this.props.type,
      model: this.props.model,
      infoLoading: this.props.infoLoading,
      drawerSecondExpress: false, //二级抽屉显示物流快递信息
      drawerSecondShopNote: false, //二级抽屉显示~商家备注信息
      drawerSecondUserAddress: false, //二级抽屉显示~用户基本信息进行编辑
      drawerSecondUserAddressLoading: false, //二级抽屉显示~用户基本信息进行编辑
      drawerSecondExpressEdit: false, //二级抽屉显示~添加/编辑物流信息
      drawerSecondExpressEditLoading: false, //二级抽屉显示~添加/编辑物流信息
      express: {}, //快递信息
      expressData: [], //快递物流详情，从快递100或者快递鸟获取信息
      expressDataPlatform: '', //快递物流详情，从快递100或者快递鸟获取信息
      expressDataLoading: false, //快递物流详情，从快递100或者快递鸟获取信息 ~ 是否获取成功
      areaLoading: false, //省市区信息是否获取成功
      //多期发货表格
      orderDeliverysSelectedRows: [],
      orderDeliverysSelectedIds: [],
      orderDeliverysSelectedIndexs: [],
      orderDeliverysHideen: false, //是否隐藏多期发货的表格
      drawerThridShopNoteLoading: false, //三级抽屉显示~编辑商家备注是否成功
      opoverVisible: false, //显示修改多期发货的卡片
      bookSpecialized: false, //是否是单期的图书，专门发货
    };
    this.getAreaAllInfo();
    this.getAllExpressInfo();
  }

  /**
   * 生命周期-属性发生变化...componentWillReceiveProps
   * 这里的nextProps，可以获取到所有的属性。
   * 目前没用，因为 dialog 每次都被销毁了
   */
  componentWillReceiveProps(nextProps) {
    if (nextProps.model) {
      const { type, model, infoLoading, ...other } = this.state;
      const modelTemp = Object.assign(this.props.model, nextProps.model);

      if (model.orderDeliverys.filter(en => typeof en.expressDeliveryMethod === 'number').length >
        modelTemp.orderDeliverys.filter(en => typeof en.expressDeliveryMethod === 'number').length) {
        // 寻找最新的 orderDeliverys 对象
        modelTemp.orderDeliverys = model.orderDeliverys;
      }

      this.state = {
        type: nextProps.type,
        model: modelTemp,
        infoLoading: nextProps.infoLoading,
        ...other,
      };
    }
  }

  getPropsByKey = prop => {
    const model = this.props.model || {};
    const finalModel = Object.assign(model, this.props.form.getFieldsValue());
    return finalModel[prop];
  };

  //获取所有的快递公司的信息
  getAllExpressInfo = () => {
    if (allExpressInfo.length > 0) {
      return;
    }
    requestPromise(getWebPath(`/express/expressList?isEnable=1&sidx=sort&order=asc`), {
      method: 'GET',
    }).then(res => {
      if (res && res.code === 0) {
        const express = res.page.list || [];
        allExpressInfo = [
          ...express.map(e => ({
            id: e.id,
            name: e.expressName,
            namePinyin: e.namePinyin,
            expressCode: e.expressCode,
            expressCodeKdniao: e.expressCodeKdniao,
          })),
        ];
      }
    });
  };

  //获取所有的省市区数据 省份
  getAreaAllInfo = () => {
    this.setState({
      areaLoading: true,
    });
    requestPromise(getWebPath(`/express/areaListAll`), {
      method: 'GET',
    }).then(res => {
      this.setState({
        areaLoading: false,
      });
      if (res && res.code === 0) {
        const areaVos = res.areaVos;
        const areaVosNew = areaVos.map(en => ({
          value: `${en.areaCode}`,
          label: en.areaName,
          level: en.level,
          id: en.id,
          pingyin: en.pingyin,
          children: en.infAreaVos.map(en2 => ({
            value: `${en2.areaCode}`,
            label: en2.areaName,
            level: en2.level,
            id: en2.id,
            pingyin: en2.pingyin,
            children: en2.infAreaVos.map(en3 => ({
              value: `${en3.areaCode}`,
              label: en3.areaName,
              level: en3.level,
              id: en3.id,
              pingyin: en3.pingyin,
            })),
          })),
        }));
        if (areaVosNew !== null && areaVosNew.length > 0) {
          areaAlloptions = areaVosNew || [];
          localStorage.setItem('areaAlloptions', JSON.stringify(areaAlloptions));
        }
      }
    });
  };

  //修改用户发货地址信息
  updateUserAddressInfo = () => {
    this.setState({
      drawerSecondUserAddress: true,
    });
  };

  //保存物流发货信息
  saveExpressInfo = () => {
    const finalModel = Object.assign(
      this.state.model.orderAddress || {},
      this.props.form.getFieldsValue().orderAddress
    );

    const id = finalModel.id;
    const expressId = finalModel.expressId;
    const expressNumber = finalModel.expressNumber;
    const expressDeliveryMethod = finalModel.expressDeliveryMethod;

    const orderAddress = { id, expressId, expressNumber, expressDeliveryMethod };

    let fieldNames = ['orderAddress.expressId', 'orderAddress.expressNumber'];
    if (expressDeliveryMethod === 1 || expressDeliveryMethod === '1') {
      fieldNames = [];
    }

    this.props.form.validateFieldsAndScroll(fieldNames, (err, values) => {
      if (!err) {
        // submit the values
        const url = '/order/updateOrderExpress';

        //立刻执行
        setTimeout(() => {
          this.setState({
            drawerSecondExpressEditLoading: true,
          });
        }, 0);

        requestPromise(getWebPath() + url, {
          method: 'POST',
          body: orderAddress,
        }).then(res => {
          this.setState({
            drawerSecondExpressEditLoading: false,
          });
          if (res && res.code === 0) {
            uiUtils.showMessage(
              formatMessage({ id: 'ours.curd.show-alert.operate-success' }),
              'success'
            );
            const orderInfo = res.order;

            // 增加属性 图书专发是完成
            orderInfo.bookSpecializedSucess =
              orderInfo.orderAddress &&
              orderInfo.orderAddress.expressDeliveryMethod !== null &&
              orderInfo.orderAddress.expressDeliveryMethod !== undefined;

            this.state.model = orderInfo;
            this.setState({
              model: orderInfo,
              drawerSecondExpressEdit: false,
            });
          }
        });
      }
    });
  };

  //保存物流发货信息~多期物流发货
  saveExpressInfoOfMultiple = () => {
    const finalModel = Object.assign(
      this.state.model.orderAddress || {},
      this.props.form.getFieldsValue().orderAddress
    );

    const orderId = finalModel.objectId || this.state.model.id;
    const expressId = finalModel.expressId;
    const expressNumber = finalModel.expressNumber;
    const expressDeliveryMethod = finalModel.expressDeliveryMethod;
    const orderDeliveryIds = this.state.orderDeliverysSelectedIds || [];

    if (orderId === null || orderId === undefined || orderId === '') {
      uiUtils.showAlert('orderId不能为空！', 'error');
      return;
    }

    const deliveryExpress = {
      orderId,
      expressDeliveryMethod,
      expressId,
      expressNumber,
      orderDeliveryIds: orderDeliveryIds.join(','),
    };

    let fieldNames = ['orderAddress.expressId', 'orderAddress.expressNumber'];
    if (expressDeliveryMethod === 1 || expressDeliveryMethod === '1') {
      fieldNames = [];
    }

    this.props.form.validateFieldsAndScroll(fieldNames, (err, values) => {
      if (!err) {
        if (orderDeliveryIds.length <= 0) {
          uiUtils.showAlert('请选择一个要发货的期数', 'error');
          return;
        }

        // submit the values
        const url = '/order/updateOrderExpressOfMultiplePeriods';

        const callback = () => {
          //立刻执行
          setTimeout(() => {
            this.setState({
              drawerSecondExpressEditLoading: true,
            });
          }, 1);
          requestPromise(getWebPath() + url, {
            method: 'POST',
            body: deliveryExpress,
            contentType: 'application/x-www-form-urlencoded',
          }).then(res => {
            this.setState({
              drawerSecondExpressEditLoading: false,
            });
            if (res && res.code === 0) {
              uiUtils.showMessage(
                formatMessage({ id: 'ours.curd.show-alert.operate-success' }),
                'success'
              );
              const order = res.order;
              this.setState({
                model: order,
                drawerSecondExpressEdit: false,
              });
            }
          });
        };

        //判断如果一次发多期的，这里提示一下
        if (orderDeliveryIds.length > 1) {
          uiUtils.showConfirm('确定一次发了多期的商品吗？', () => {
            callback();
          });
        } else {
          callback();
        }
      }
    });
  };

  //保存用户发货地址信息
  saveUserAddressInfo = () => {
    const finalModel = Object.assign(
      this.state.model.orderAddress || {},
      this.props.form.getFieldsValue().orderAddress
    );

    const areaOptionCur = finalModel.areaOptionCur;
    const id = finalModel.id;
    const provinceCode = areaOptionCur[0];
    const cityCode = areaOptionCur[1];
    const areaCode = areaOptionCur[2];
    const receiveName = finalModel.receiveName;
    const receiveTel = finalModel.receiveTel;
    const receiveAddress = finalModel.receiveAddress;

    const orderAddress = {
      id,
      provinceCode,
      areaCode,
      cityCode,
      receiveName,
      receiveTel,
      receiveAddress,
    };

    this.props.form.validateFieldsAndScroll(
      [
        'orderAddress.receiveName',
        'orderAddress.receiveTel',
        'orderAddress.areaOptionCur',
        'orderAddress.receiveAddress',
      ],
      (err, values) => {
        if (!err) {
          const url = '/order/updateOrderAddress';
          this.setState({
            drawerSecondUserAddressLoading: true,
          });

          requestPromise(getWebPath() + url, {
            method: 'POST',
            body: orderAddress,
          }).then(res => {
            this.setState({
              expressDataLoading: true,
            });
            if (res && res.code === 0) {
              uiUtils.showMessage(
                formatMessage({ id: 'ours.curd.show-alert.operate-success' }),
                'success'
              );
              const order = res.order;
              this.setState({
                model: order,
                drawerSecondUserAddress: false,
                drawerSecondUserAddressLoading: false,
              });
            }
          });
        }
      }
    );
  };

  //添加商家备注信息
  addShopNoteEdit = () => {
    this.setState({
      drawerSecondShopNote: true,
    });
  };

  //保存商家备注信息
  saveShopNotes = (orderId, shopNote) => {
    //不能双向绑定，这里只能原对象、新对象进行合并.
    const order = { id: orderId, shopNote };
    // submit the values
    const url = '/order/update';

    this.setState({
      drawerThridShopNoteLoading: true,
    });
    requestPromise(getWebPath() + url, {
      method: 'POST',
      body: order,
    }).then(res => {
      if (res && res.code === 0) {
        uiUtils.showMessage(
          formatMessage({ id: 'ours.curd.show-alert.operate-success' }),
          'success'
        );

        const orderVo = res.order;
        this.setState({
          model: orderVo,
          drawerSecondShopNote: false,
          drawerThridShopNoteLoading: false,
        });
      }
    });
  };

  //获取快递信息
  getExpressInfo = (expressCode, expressNumber) => {
    const expressData = [];
    if (expressCode == null || expressCode === undefined || expressCode.length <= 0) {
      this.setState({
        expressData,
      });
      return expressData;
    }
    this.setState({
      expressDataLoading: true,
    });
    requestPromise(
      getWebPath(
        `/api/userRelated/expressLogistics?expressCode=${expressCode}&expressLogisticsNo=${expressNumber}`
      ),
      {
        method: 'GET',
      }
    ).then(res => {
      if (res && res.code === 0) {
        //快递100
        if (res.object.logisticsResultKuadi100) {
          if (
            res.object.logisticsResultKuadi100.data &&
            res.object.logisticsResultKuadi100.data.length > 0
          ) {
            for (let i = 0; i < res.object.logisticsResultKuadi100.data.length; i += 1) {
              expressData.push(
                <Timeline.Item>
                  {res.object.logisticsResultKuadi100.data[i].time}&nbsp;
                  {res.object.logisticsResultKuadi100.data[i].context}
                </Timeline.Item>
              );
            }
          } else {
            expressData.push(
              <Timeline.Item>{res.object.logisticsResultKuadi100.message}</Timeline.Item>
            );
          }
        } else if (res.object.logisticsResultKdNiao) {
          //快递鸟
          if (
            res.object.logisticsResultKdNiao.Traces &&
            res.object.logisticsResultKdNiao.Traces.length > 0
          ) {
            for (let i = 0; i < res.object.logisticsResultKdNiao.Traces.length; i += 1) {
              const traces = res.object.logisticsResultKdNiao.Traces[i];
              expressData.push(
                <Timeline.Item>
                  {`${traces.AcceptTime}`}&nbsp;
                  {`${traces.AcceptStation}`}
                </Timeline.Item>
              );
            }
            //这里反转一下数据：
            expressData.reverse();
          } else {
            expressData.push(
              <Timeline.Item>{res.object.logisticsResultKdNiao.Reason}</Timeline.Item>
            );
          }
        }
      } else if (res.object) {
        expressData.push(<Timeline.Item>{res.object.msg || res.msg || ''}</Timeline.Item>);
      } else {
        expressData.push(<Timeline.Item>{res.msg || ''}</Timeline.Item>);
      }

      this.setState({
        expressDataLoading: false,
        expressDataPlatform: res.object ? res.object.platformType || '' : '',
        expressData,
      });
    });
    return expressData;
  };

  //修改多期发货周期
  updateDeliveryTime = (val, orderId) => {
    const startDate = `${val[0].format('YYYY-MM')}-01`;
    const endDate = `${val[1].format('YYYY-MM')}-01`;
    const url = `/order/updateDeliveryTime?orderId=${orderId}&startDate=${startDate}&endDate=${endDate}`;

    //立刻执行
    setTimeout(() => {
      this.setState({
        drawerSecondExpressEditLoading: true,
      });
    }, 1);

    requestPromise(getWebPath() + url, {
      method: 'GET',
    }).then(res => {
      if (res && res.code === 0) {
        uiUtils.showMessage(
          formatMessage({ id: 'ours.curd.show-alert.operate-success' }),
          'success'
        );
        const order = res.order;
        //loading
        this.setState({
          opoverVisible: false,
          drawerSecondExpressEditLoading: false,
          model: order,
        });
      }
    });
  };

  deliverPopconfirmToConfirm = model => {
    if (model.deliveryType === 0 && model.deliveryExpressType !== 'A') {
      //1: 以前的快递单号干掉，快递公司不干掉
      const expressDeliveryMethod = 0;
      const expressId = '';
      const expressNumber = '';
      const newModel = {
        ...model,
        orderAddress: { expressDeliveryMethod, expressId, expressNumber },
      };

      //this.setState是异步的这里让同步立即执行
      setTimeout(() => {
        this.setState({
          model: newModel,
        });
      }, 1);

      //2: 并且默认选中最新etable的第一条数据
      const dataSource = this.state.model.orderDeliverys.filter(
        en =>
          en.expressDeliveryMethod === null ||
          en.expressDeliveryMethod === undefined ||
          en.expressDeliveryMethod === ''
      );
      if (dataSource.length > 0) {
        const selectedRows = [dataSource[0]];
        const selectedIds = [dataSource[0].id];
        const selectedIndexs = [0];

        this.setState({
          orderDeliverysSelectedRows: selectedRows,
          orderDeliverysSelectedIds: selectedIds,
          orderDeliverysSelectedIndexs: selectedIndexs,
        });
      }
    }

    this.setState({
      drawerSecondExpressEdit: true,
      orderDeliverysHideen: false,
    });
  };

  render() {
    const type = this.state.type; //编辑是：新增（add）、编辑(edit)、复制(copy)、还是查看(view)
    const model = this.state.model || { orderDetailVos: [], orderDeliverys: [] };
    this.state.model = model;
    const orderDetailVos = this.state.model ? this.state.model.orderDetailVos : [];
    this.state.model.orderDetailVos = orderDetailVos;
    let orderAddress = this.state.model.orderAddress;
    let orderInvoice = this.state.model.orderInvoice;
    if (orderAddress === undefined || orderAddress === null) {
      orderAddress = {
        receiveName: '',
        receiveTel: '',
        receiveProvinceName: '',
        receiveCountyName: '',
        receiveAddress: '',
        provinceCode: '',
        cityCode: '',
        areaCode: '',
        expressCode: '',
        expressNumber: '',
        expressName: '',
        officialWebsite: '',
        icon: '',
      };
    }
    //查询当前的快递单的，快递号
    const express = this.state.express || {
      expressCode: '',
      expressNumber: '',
      officialWebsite: '',
      icon: '',
    };
    this.state.model.express = express;
    //省市区
    orderAddress.areaOptionCur = [
      `${orderAddress.provinceCode}`,
      `${orderAddress.cityCode}`,
      `${orderAddress.areaCode}`,
    ];
    this.state.model.orderAddress = orderAddress;

    if (orderInvoice === undefined || orderInvoice === null) {
      orderInvoice = {
        invoiceHeadType: null,
        invoiceHeadName: '',
        taxpayersNo: '',
        companyAddress: '',
        companyTel: '',
        companyBankName: '',
        companyCarid: '',
      };
      this.state.model.orderInvoice = orderInvoice;
    }
    const infoLoading = this.state.infoLoading;
    const {
      form,
      form: { getFieldDecorator, getFieldValue, setFieldsValue },
    } = this.props;
    const formItemLayout = {
      labelCol: { span: 5 },
      wrapperCol: { span: 18 }, //5+19=24,少一个栅格
    };
    const colSpanLayout = { md: 12, sm: 24 }; //每一col跨?列
    const colSpanLayoutForUserEdit = { md: 24, sm: 24 }; //每一col跨?列
    const rowGutterPxLayout = { md: 24, sm: 16 }; //col之间的间隔?px
    const inputCodeDisabled = {
      disabled: type === 'update',
    };
    const gridStyle = {
      width: '50%',
      padding: '10px',
      paddingLeft: '30px',
      paddingRight: '30px',
      textAlign: 'left',
    };
    const gridUserStyle = {
      width: '100%',
      padding: '10px',
      paddingLeft: '30px',
      paddingRight: '30px',
      textAlign: 'left',
    };
    const gridTextStyle = {
      float: 'right',
      fontSize: '14px',
      display: 'inline-block',
      whitespace: 'nowrap',
      overflow: 'hidden',
      textOverflow: 'ellipsis',
    };
    const CardInfo = ({ num, price, giftId }) => (
      <div style={{ marginTop: 5 }}>
        <div>
          <span style={{ color: 'blue' }}>x{num}</span>
          <span style={{ color: 'red' }}>
            {giftId !== undefined && giftId !== null ? '赠品' : ''}
          </span>
          <span style={{ float: 'right' }}>{price}</span>
        </div>
      </div>
    );
    const customDot = (dot, { status, index, title, description }) => (
      <Popover
        content={
          <span>
            {title} {description}
          </span>
        }
      >
        {dot}
      </Popover>
    );
    //校验文档：https://ant.design/components/form-cn/#%E6%A0%A1%E9%AA%8C%E8%A7%84%E5%88%99
    return (
      <Fragment>
        <Fragment>
          {/*订单进度信息*/}
          <Card bordered hoverable size="small" style={{ marginBottom: 20 }}>
            <Card.Grid style={gridUserStyle}>
              {model.statusOrder !== 5 && (
                <Fragment>
                  <Steps
                    progressDot={customDot}
                    current={model.statusOrder === 4 ? 3 : model.statusOrder}
                    size="small"
                  >
                    <Steps.Step
                      title="买家下单"
                      description={<span style={{ fontSize: '5px' }}>{model.createTime}</span>}
                    />
                    <Steps.Step
                      title="买家付款"
                      description={<span style={{ fontSize: '5px' }}>{model.timePayOrder}</span>}
                    />
                    <Steps.Step
                      title="商家发货"
                      style={{ display: model.statusOrder === 5 ? 'none' : 'block' }}
                      description={
                        <span style={{ fontSize: '5px' }}>{model.timeDeliveryOrder}</span>
                      }
                    />
                    <Steps.Step
                      title={model.statusOrder === 4 ? '交易完成' : '买家收货'}
                      description={
                        model.statusOrder === 4 ? (
                          <span style={{ fontSize: '5px' }}>{model.timeCommentsOrder}</span>
                        ) : (
                          <span style={{ fontSize: '8px' }}>{model.timeConfirmOrder}</span>
                        )
                      }
                    />
                  </Steps>
                </Fragment>
              )}
              {model.statusOrder === 5 && (
                <Fragment>
                  <Steps
                    progressDot={customDot}
                    current={model.statusOrder === 0 ? 0 : model.statusOrder === 5 ? 1 : 0}
                    size="small"
                  >
                    <Steps.Step
                      title="买家下单"
                      description={<span style={{ fontSize: '5px' }}>{model.createTime}</span>}
                    />
                    <Steps.Step
                      title="交易关闭"
                      description={<span style={{ fontSize: '5px' }}>{model.timeCancleOrder}</span>}
                    />
                  </Steps>
                </Fragment>
              )}
            </Card.Grid>
          </Card>
          {/*订单基本信息*/}
          <Card
            bordered
            hoverable
            size="small"
            bodyStyle={{ paddingBottom: 10 }}
            style={{ marginBottom: 20 }}
            title="订单基本信息"
          >
            <Card.Grid style={gridStyle}>
              <span>订单号</span>
              <span style={gridTextStyle}>{model.orderNo}</span>
            </Card.Grid>
            <Card.Grid style={gridStyle}>
              <span>支付方式</span>
              <span style={gridTextStyle}>{model.payTypeStr}</span>
            </Card.Grid>
            <Card.Grid style={gridStyle}>
              <span>支付时间</span>
              <span style={gridTextStyle}>{model.timePayOrder}</span>
            </Card.Grid>
            <Card.Grid style={gridStyle}>
              <span>下单时间</span>
              <span style={gridTextStyle}>{model.timePlaceOrder}</span>
            </Card.Grid>
            <Card.Grid style={gridStyle}>
              <span>订单类型</span>
              <span style={gridTextStyle}>{model.orderPromotionTypeStr}</span>
            </Card.Grid>
            <Card.Grid style={gridStyle}>
              <span>订单来源</span>
              <span style={gridTextStyle}>
                {model.orderSourceStr}{' '}
                {model.orderImportPlatformName !== null &&
                model.orderImportPlatformName !== undefined
                  ? model.orderImportPlatformName
                  : ''}
              </span>
            </Card.Grid>
            <Card.Grid style={gridStyle}>
              <span>商品总价</span>
              <span style={gridTextStyle}>￥{numeral(model.priceTotal).format('0,0.00')}</span>
            </Card.Grid>
            <Card.Grid style={gridStyle}>
              <span>取消时间</span>
              <span style={gridTextStyle}>{model.timeCancleOrder}</span>
            </Card.Grid>
            <Card.Grid style={gridStyle}>
              <span>订单总价</span>
              <span style={gridTextStyle}>￥{numeral(model.priceFinal).format('0,0.00')}</span>
            </Card.Grid>
            <Card.Grid style={gridStyle}>
              <span>发货时间</span>
              <span style={gridTextStyle}>{model.timeDeliveryOrder}</span>
            </Card.Grid>
            <Card.Grid style={gridStyle}>
              <span>运费价格</span>
              <span style={gridTextStyle}>￥{numeral(model.pricePostage).format('0,0.00')}</span>
            </Card.Grid>
            <Card.Grid style={gridStyle}>
              <span>支付金额</span>
              <span style={gridTextStyle}>
                {model.pricePayed === null || model.pricePayed === undefined
                  ? '-'
                  : `￥${numeral(model.pricePayed).format('0,0.00')}`}
              </span>
            </Card.Grid>
            <Card.Grid style={gridStyle}>
              <span>订单状态</span>
              <span style={{ ...gridTextStyle }}>
                <Tag color="magenta">{model.statusOrderStr}</Tag>
              </span>
            </Card.Grid>
            <Card.Grid style={gridStyle}>
              <span>取消/关闭原因</span>
              <span style={gridTextStyle}>
                {model.cancleOrderReason === null || model.cancleOrderReason === undefined
                  ? '-'
                  : `${model.cancleOrderReason}`}
              </span>
            </Card.Grid>
          </Card>
          {/*订单详情*/}
          <Card
            bordered
            hoverable
            size="small"
            bodyStyle={{ paddingBottom: 10 }}
            style={{ marginBottom: 20 }}
            title="订单详情"
          >
            <List
              rowKey="id"
              style={{ marginTop: 24 }}
              grid={{ gutter: 24, xl: 4, lg: 3, md: 3, sm: 2, xs: 1 }}
              loading={infoLoading}
              dataSource={orderDetailVos}
              renderItem={item => (
                <List.Item key={item.id}>
                  <Card
                    hoverable
                    bodyStyle={{ paddingBottom: 10 }}
                    cover={
                      <Zmage
                        src={
                          `${item.productImgs}`.includes(',')
                            ? item.productImgs.split(',')[0]
                            : `${item.productImgs}`
                        }
                        alt={item.productTitle || item.productName}
                        width={100}
                      />
                    }
                  >
                    <Card.Meta title="" description={item.productTitle || item.productName} />
                    <CardInfo
                      num={item.productBuyNumber}
                      price={item.productPrice}
                      giftId={item.giftId}
                    />
                  </Card>
                </List.Item>
              )}
            />
          </Card>
          {/*费用信息*/}
          <Card
            bordered
            hoverable
            size="small"
            bodyStyle={{ paddingBottom: 10 }}
            style={{ marginBottom: 20, marginTop: 20 }}
            title="费用信息"
          >
            <Card.Grid style={gridUserStyle}>
              <span style={gridTextStyle}>
                商品总金额：{`${numeral(model.priceTotal).format('0,0.00')}`} + 发票税额：￥0.00 +
                运费价格：{`${numeral(model.pricePostage).format('0,0.00')}`} + 包装价格：￥0.00
              </span>
            </Card.Grid>
            <Card.Grid style={gridUserStyle}>
              <span style={gridTextStyle}>
                订单总金额：{`${numeral(model.priceFinal).format('0,0.00')}`}
              </span>
            </Card.Grid>
            <Card.Grid style={gridUserStyle}>
              <span style={{ ...gridTextStyle, fontWeight: 'bolder' }}>
                - 优惠金额：{`${numeral(model.pricePreferential).format('0,0.00')}`} -
                抵扣金额：￥0.00 - 新户立减：￥0.00{' '}
              </span>
            </Card.Grid>
            <Card.Grid style={gridUserStyle}>
              <span style={gridTextStyle}>
                = 应付款金额：{`${numeral(model.pricePayed).format('0,0.00')}`}
              </span>
            </Card.Grid>
          </Card>
          {/*发票信息*/}
          <Card
            bordered
            hoverable
            size="small"
            bodyStyle={{ paddingBottom: 10 }}
            style={{ marginBottom: 20, marginTop: 20 }}
            title="发票信息"
            loading={infoLoading}
          >
            <Card.Grid style={gridUserStyle}>
              <span>发票类型</span>
              <span style={gridTextStyle}>
                {model.orderInvoice.invoiceHeadType === 11
                  ? '个人发票'
                  : model.orderInvoice.invoiceHeadType === 12
                  ? '公司发票'
                  : '无开发票信息'}
              </span>
            </Card.Grid>
            <Card.Grid style={gridUserStyle}>
              <span>发票抬头</span>
              <span style={gridTextStyle}>{model.orderInvoice.invoiceHeadName}</span>
            </Card.Grid>
            <Card.Grid style={gridUserStyle}>
              <span>纳税人识别号</span>
              <span style={{ ...gridTextStyle, fontWeight: 'bolder' }}>
                {model.orderInvoice.taxpayersNo}
              </span>
            </Card.Grid>
            <Card.Grid style={gridUserStyle}>
              <span>注册地址</span>
              <span style={gridTextStyle}>{model.orderInvoice.companyAddress}</span>
            </Card.Grid>
            <Card.Grid style={gridUserStyle}>
              <span>注册电话</span>
              <span style={gridTextStyle}>{model.orderInvoice.companyTel}</span>
            </Card.Grid>
            <Card.Grid style={gridUserStyle}>
              <span>开户银行</span>
              <span style={gridTextStyle}>{model.orderInvoice.companyBankName}</span>
            </Card.Grid>
            <Card.Grid style={gridUserStyle}>
              <span>银行账号</span>
              <span style={gridTextStyle}>{model.orderInvoice.companyCarid}</span>
            </Card.Grid>
          </Card>
          {/*订单收货人信息、发货信息*/}
          <Form layout="inline">
            <Row gutter={{ ...rowGutterPxLayout }}>
              <Spin spinning={infoLoading}>
                <Col {...colSpanLayout}>
                  {/*订单收货人信息*/}
                  <Card
                    bordered
                    hoverable
                    size="small"
                    bodyStyle={{ padding: 0, margin: 0 }}
                    style={{ marginBottom: 0 }}
                    title="订单收货人信息"
                    extra={
                      <Fragment>
                        <CopyToClipboard
                          text={`收货人：${orderAddress.receiveName} 、\n联系方式：${
                            orderAddress.receiveTel
                          }、\n详细地址：${orderAddress.receiveProvinceName}${
                            orderAddress.receiveCityName
                          }${orderAddress.receiveCountyName}${orderAddress.receiveAddress}`}
                          onCopy={() => {
                            uiUtils.showMessage(
                              formatMessage({ id: 'ours.curd.list.msg.copySuccess' }),
                              'success'
                            );
                          }}
                        >
                          <Button
                            type="primary"
                            style={{ fontSize: '12px' }}
                            size="small"
                            loading={this.state.areaLoading}
                          >
                            <FormattedMessage id="ours.curd.list.copy" defaultMessage="复制" />
                          </Button>
                        </CopyToClipboard>
                        <Button
                          type="primary"
                          style={{ fontSize: '12px', marginLeft: '10px' }}
                          size="small"
                          /*disabled={
                            model.orderSource !== undefined &&
                            model.orderSource !== null &&
                            model.orderSource === 6
                          }*/
                          loading={this.state.areaLoading}
                          onClick={this.updateUserAddressInfo}
                        >
                          <FormattedMessage id="ours.curd.list.edit" defaultMessage="编辑" />
                        </Button>
                      </Fragment>
                    }
                  />
                  <Card.Grid style={{ width: '100%', padding: '0', margin: '0' }}>
                    <div style={{ paddingTop: '20px', backgroundColor: '#eee' }}>
                      <div style={{ textAlign: 'center' }}>
                        <Avatar
                          style={{ backgroundColor: '#87d068' }}
                          size={80}
                          icon="user"
                          src={model.headPortraitImg}
                          alt={model.username}
                        />
                      </div>
                      <span
                        style={{
                          display: 'block',
                          textAlign: 'center',
                          color: '#000',
                          fontSize: '12px',
                          margin: '5px',
                        }}
                      >
                        <Icon type="user" />
                        &nbsp;&nbsp;{model.username}
                      </span>
                      <span
                        style={{
                          display: 'block',
                          textAlign: 'center',
                          color: '#000',
                          fontSize: '12px',
                          margin: '5px',
                        }}
                      >
                        <Icon type="mobile" />
                        &nbsp;&nbsp;{model.mobile}
                      </span>
                    </div>
                    <Card.Grid style={gridUserStyle}>
                      <span>
                        <Icon type="user" />
                        收货人
                      </span>
                      <span style={gridTextStyle}>{orderAddress.receiveName}</span>
                    </Card.Grid>
                    <Card.Grid style={gridUserStyle}>
                      <span>
                        <Icon type="mobile" />
                        联系方式
                      </span>
                      <span style={gridTextStyle}>{orderAddress.receiveTel}</span>
                    </Card.Grid>
                    <Card.Grid style={gridUserStyle}>
                      <span>
                        <Icon type="environment" />
                        收货地址
                      </span>
                      <span style={{ ...gridTextStyle, fontWeight: 'bolder' }}>
                        {orderAddress.receiveProvinceName !== undefined &&
                        orderAddress.receiveProvinceName !== null
                          ? orderAddress.receiveProvinceName
                          : ''}
                        {orderAddress.receiveCityName !== undefined &&
                        orderAddress.receiveCityName !== null
                          ? orderAddress.receiveCityName
                          : ''}
                        {orderAddress.receiveCountyName !== undefined &&
                        orderAddress.receiveCountyName !== null
                          ? orderAddress.receiveCountyName
                          : ''}
                        {orderAddress.receiveAddress}
                      </span>
                    </Card.Grid>
                    <Card.Grid style={gridUserStyle}>
                      <span>
                        <Icon type="tag" />
                        用户备注
                      </span>
                      <span style={gridTextStyle}>{model.userNote}</span>
                    </Card.Grid>
                    <Card.Grid style={gridUserStyle}>
                      <span>
                        <Icon type="tags" />
                        商家备注
                        <Button
                          type="primary"
                          style={{ fontSize: '12px' }}
                          size="small"
                          onClick={this.addShopNoteEdit}
                        >
                          <FormattedMessage id="ours.curd.list.edit" defaultMessage="编辑" />
                        </Button>
                      </span>
                      <p style={gridTextStyle} title={model.shopNote}>
                        {model.shopNote}
                      </p>
                    </Card.Grid>
                  </Card.Grid>
                </Col>
              </Spin>
              <Col {...colSpanLayout}>
                {/*配送信息*/}
                <Card
                  loading={infoLoading}
                  bordered
                  hoverable
                  size="small"
                  bodyStyle={{ paddingBottom: 10 }}
                  style={{ marginBottom: 20 }}
                  title="发货信息"
                  extra={
                    <Fragment>
                      {/*打印按钮进行打印*/}
                      <ReactToPrint
                        trigger={() => (
                          <Button type="primary" size="small">
                            打印
                          </Button>
                        )}
                        content={() => this.componentRef}
                      />
                      {
                        /*发货按钮，进行发货*/
                        <Button
                          type="primary"
                          disabled={
                            !(
                              model.statusOrder === 1 &&
                              model.isNeedDelivery === true &&
                              //整单发货，还没发过货
                              ((model.deliveryExpressType === 'A' &&
                                (orderAddress.expressDeliveryMethod === null ||
                                  orderAddress.expressDeliveryMethod === undefined)) ||
                                //多期发货，还有待发货的期数
                                (model.deliveryExpressType !== 'A' &&
                                  this.state.model.orderDeliverys.filter(
                                    en =>
                                      en.expressDeliveryMethod === null ||
                                      en.expressDeliveryMethod === undefined ||
                                      en.expressDeliveryMethod === ''
                                  ).length > 0))
                            )
                          }
                          onClick={() => {
                            if (model.existRefundsRecord || false) {
                              uiUtils.showConfirm('该订单存在退款记录，是否确认继续发货？', () => {
                                this.state.bookSpecialized = false;
                                if (model.deliveryExpressType === 'A') {
                                  this.state.bookSpecialized = true;
                                }
                                this.deliverPopconfirmToConfirm(model);
                              });
                            } else {
                              this.state.bookSpecialized = false;
                              if (model.deliveryExpressType === 'A') {
                                this.state.bookSpecialized = true;
                              }
                              this.deliverPopconfirmToConfirm(model);
                            }
                          }}
                          size="small"
                        >
                          发货
                        </Button>
                      }

                      {/*如果是混合发货，这里增加一个图书专发的按钮，只进行图书单次发货*/}
                      <Button
                        type="primary"
                        hidden={
                          !(
                            model.statusOrder === 1 &&
                            model.isNeedDelivery === true &&
                            //整单发货，还没发过货
                            (model.deliveryExpressType === 'D' &&
                              !model.bookSpecializedSucess === true)
                          )
                        }
                        onClick={() => {
                          if (model.existRefundsRecord || false) {
                            uiUtils.showConfirm(
                              '该订单存在退款记录，是否确认继续发货(图书专发)？',
                              () => {
                                this.state.bookSpecialized = true;
                                this.deliverPopconfirmToConfirm(model);
                              }
                            );
                          } else {
                            this.state.bookSpecialized = true;
                            this.deliverPopconfirmToConfirm(model);
                          }
                        }}
                        size="small"
                      >
                        发货(图书专发)
                      </Button>

                      {/*多期发货的修改周期,多期发货&&还没发完*/}
                      {model.deliveryType === 0 &&
                        model.deliveryExpressType === 'C' &&
                        model.isNeedDelivery === true && (
                          <Popover
                            visible={this.state.opoverVisible}
                            placement="bottomRight"
                            title="修改发货周期"
                            content={
                              <div>
                                <Form layout="horizontal" style={{ marginBottom: 200 }}>
                                  <FormItem label="发货周期" {...formItemLayout}>
                                    {getFieldDecorator('DeliveryStartEnd', {
                                      initialValue: this.state.DeliveryStartEnd,
                                      rules: [
                                        {
                                          required: true,
                                          message: '请选择发货周期',
                                        },
                                      ],
                                    })(
                                      <ControlledRangePicker
                                        onPanelChange={val => {
                                          this.setState({
                                            DeliveryStartEnd: val,
                                          });
                                        }}
                                      />
                                    )}
                                  </FormItem>
                                </Form>
                                <div
                                  style={{
                                    position: 'absolute',
                                    left: 0,
                                    bottom: 0,
                                    width: '100%',
                                    borderTop: '1px solid #e9e9e9',
                                    padding: '10px 16px',
                                    background: '#fff',
                                    textAlign: 'right',
                                  }}
                                >
                                  <Button
                                    onClick={() => {
                                      this.setState({
                                        opoverVisible: false,
                                        drawerSecondExpressEdit: false,
                                      });
                                    }}
                                    style={{ marginRight: 8 }}
                                  >
                                    <FormattedMessage
                                      id="ours.curd.add.cancel"
                                      defaultMessage="取消"
                                    />
                                  </Button>
                                  <Button
                                    onClick={() => {
                                      const deliveryStartEnd = this.state.DeliveryStartEnd;
                                      if (
                                        deliveryStartEnd !== undefined &&
                                        deliveryStartEnd.length === 2
                                      ) {
                                        // console.log(this.props.form.getFieldsValue())
                                        // console.log(model)
                                        this.updateDeliveryTime(deliveryStartEnd, model.id);
                                      } else {
                                        //提示
                                        notification.open({
                                          message: '提示',
                                          description: '请选择周期。',
                                          onClick: () => {},
                                        });
                                      }
                                    }}
                                    loading={this.state.drawerSecondExpressEditLoading}
                                    type="primary"
                                  >
                                    <FormattedMessage
                                      id="ours.curd.add.save"
                                      defaultMessage="保存"
                                    />
                                  </Button>
                                </div>
                              </div>
                            }
                            trigger="click"
                          >
                            <Button
                              type="primary"
                              size="small"
                              onClick={() => {
                                // this.state.DeliveryStartEnd
                                // setTimeout(() => {
                                //   this.setState({
                                //     DeliveryStartEnd: [],
                                //   });
                                // }, 1);
                                this.setState({
                                  opoverVisible: true,
                                  DeliveryStartEnd: [],
                                });
                              }}
                            >
                              修改发货周期
                            </Button>
                          </Popover>
                        )}
                    </Fragment>
                  }
                >
                  {// 查看整单发货的物流信息(整单发货、混合发货)
                  model.deliveryType === 0 &&
                    (model.deliveryExpressType === 'A' ||
                      (model.deliveryExpressType === 'D' && !model.deliveryExpressTypeDSingle)) && (
                      <Fragment>
                        <Card title="整单发货|图书发货">
                          <div>
                            <Card.Grid style={gridUserStyle}>
                              <span>快递公司</span>
                              <span style={gridTextStyle}>{orderAddress.expressName}</span>
                            </Card.Grid>
                            <Card.Grid style={gridUserStyle}>
                              <span>快递单号</span>
                              <span style={gridTextStyle}>{orderAddress.expressNumber}</span>
                            </Card.Grid>
                            <span
                              hidden={
                                (typeof orderAddress.expressDeliveryMethod === 'number' &&
                                  orderAddress.expressDeliveryMethod === 1) ||
                                typeof orderAddress.expressDeliveryMethod !== 'number'
                              }
                            >
                              <Card.Grid style={gridUserStyle}>
                                <Button
                                  type="primary"
                                  onClick={() => {
                                    this.setState({
                                      express: {
                                        icon: orderAddress.icon || '',
                                        officialWebsite: orderAddress.officialWebsite || '',
                                        expressCode: orderAddress.expressCode,
                                        expressNumber: orderAddress.expressNumber,
                                      },
                                      drawerSecondExpress: true,
                                    });
                                    this.getExpressInfo(
                                      orderAddress.expressCode,
                                      orderAddress.expressNumber
                                    );
                                  }}
                                  style={{ fontSize: '12px' }}
                                  size="small"
                                >
                                  查看物流
                                </Button>
                              </Card.Grid>
                            </span>
                            <span hidden={!(model.statusOrder === 1 || model.statusOrder === 2 || model.statusOrder === 3)}>
                              <Card.Grid style={gridUserStyle}>
                                <Tooltip
                                  placement="top"
                                  style={{ marginLeft: '20px' }}
                                  title="已经发货的订单，15天内可以修改发货信息，请谨慎填写"
                                >
                                  <Button
                                    type="primary"
                                    style={{ fontSize: '12px' }}
                                    icon="question-circle"
                                    disabled={orderAddress.timeDeliveryOrderModify === 'false'}
                                    onClick={() => {
                                      this.setState({
                                        drawerSecondExpressEdit: true,
                                        orderDeliverysHideen: true,
                                        bookSpecialized: true,
                                      });
                                    }}
                                    size="small"
                                  >
                                    修改发货
                                  </Button>
                                </Tooltip>
                              </Card.Grid>
                            </span>
                          </div>
                        </Card>
                      </Fragment>
                    )}
                  {// 查看多次发货信息 (多期发货、混合发货)
                  model.deliveryType === 0 &&
                    (model.deliveryExpressType === 'C' || model.deliveryExpressType === 'D') && (
                      <Card title="多期杂志|混合发货">
                        <List
                          rowKey="id"
                          style={{ marginTop: 2 }}
                          loading={infoLoading}
                          dataSource={model.orderDeliverys}
                          renderItem={item => (
                            <List.Item
                              key={item.id}
                              actions={[
                                <a
                                  style={{
                                    display:
                                      item.expressId !== null && item.expressId !== undefined
                                        ? 'block'
                                        : 'none',
                                  }}
                                  onClick={() => {
                                    this.setState({
                                      express: {
                                        icon: item.icon,
                                        officialWebsite: item.officialWebsite,
                                        expressCode: item.expressCode,
                                        expressNumber: item.expressNumber,
                                      },
                                      drawerSecondExpress: true,
                                    });
                                    this.getExpressInfo(item.expressCode, item.expressNumber);
                                  }}
                                >
                                  查看
                                </a>,
                                <a
                                  style={{
                                    display:
                                      item.timeDeliveryOrderModify === true &&
                                      model.statusOrder === 1 &&
                                      item.expressDeliveryMethod !== null &&
                                      item.expressDeliveryMethod !== undefined
                                        ? 'block'
                                        : 'none',
                                  }}
                                  onClick={() => {
                                    const expressDeliveryMethod = item.expressDeliveryMethod;
                                    const expressId = item.expressId;
                                    const expressNumber = item.expressNumber;

                                    const selectedRows = [item];
                                    const selectedIds = [item.id];
                                    const selectedIndexs = [-1];

                                    const newModel = {
                                      ...model,
                                      orderAddress: {
                                        expressDeliveryMethod,
                                        expressId,
                                        expressNumber,
                                      },
                                    };

                                    this.setState({
                                      drawerSecondExpressEdit: true,
                                      orderDeliverysHideen: true,
                                      orderDeliverysSelectedRows: selectedRows,
                                      orderDeliverysSelectedIds: selectedIds,
                                      orderDeliverysSelectedIndexs: selectedIndexs,
                                      model: newModel,
                                      bookSpecialized: false,
                                    });
                                  }}
                                >
                                  修改
                                </a>,
                              ]}
                            >
                              <List.Item.Meta
                                avatar={<Avatar src={item.icon} />}
                                title={`${item.belongMonth.substring(0, 7)}期 ${
                                  item.expressDeliveryMethod === 0
                                    ? item.expressName === undefined
                                      ? ''
                                      : item.expressName
                                    : item.expressDeliveryMethod === 1
                                    ? '无需物流'
                                    : ''
                                }`}
                                description={item.expressNumber || ''}
                              />
                            </List.Item>
                          )}
                        />
                      </Card>
                    )}
                  {// 看是否还需要发货
                  model.statusOrder === 1 &&
                    model.isNeedDelivery === true &&
                    //整单发货，还没发过火
                    ((model.deliveryExpressType === 'A' &&
                      (orderAddress.expressDeliveryMethod === null ||
                        orderAddress.expressDeliveryMethod === undefined)) ||
                      //多期发货，还有待发货的期数
                      (model.deliveryExpressType !== 'A' &&
                        this.state.model.orderDeliverys.filter(
                          en =>
                            en.expressDeliveryMethod === null ||
                            en.expressDeliveryMethod === undefined ||
                            en.expressDeliveryMethod === ''
                        ).length > 0)) && (
                      <Fragment>
                        <Alert message="还有未发完的货品" type="warning" />
                      </Fragment>
                    )}
                </Card>
              </Col>
            </Row>
          </Form>
        </Fragment>
        <Drawer
          title="查看物流信息"
          width={420}
          closable
          visible={this.state.drawerSecondExpress}
          onClose={() => {
            this.setState({
              drawerSecondExpress: false,
            });
          }}
        >
          <Card loading={this.state.expressDataLoading}>
            <Card.Grid style={gridUserStyle}>
              <Avatar shape="square" size={40} icon="user" src={express.icon || ''} />
              <span>&nbsp;&nbsp;&nbsp;&nbsp;{express.expressName}</span>
              <span>
                &nbsp;&nbsp;&nbsp;&nbsp;
                <CopyToClipboard
                  text={express.expressNumber}
                  onCopy={() => {
                    uiUtils.showMessage(
                      formatMessage({ id: 'ours.curd.list.msg.copySuccess' }),
                      'success'
                    );
                  }}
                >
                  <a
                    href={express.officialWebsite}
                    rel="noreferrer noopener"
                    target="_blank"
                    title={express.expressName}
                  >
                    {express.expressNumber}
                  </a>
                </CopyToClipboard>
                <span>
                  &nbsp;&nbsp;&nbsp;&nbsp;
                  <Tooltip
                    placement="top"
                    title={`数据来源${
                      this.state.expressDataPlatform === 1
                        ? '快递鸟'
                        : this.state.expressDataPlatform === 2
                        ? '快递100'
                        : '阿里物流'
                    }`}
                  >
                    <Button
                      icon="question-circle"
                      size="small"
                      onClick={() => {
                        const url =
                          this.state.expressDataPlatform === 1
                            ? 'https://www.kdniao.com/'
                            : this.state.expressDataPlatform === 2
                            ? 'https://www.kuaidi100.com/'
                            : 'https://www.cainiao.com/markets/cnwww/kuaidi-landing';
                        window.open(`${url}`, '_blank');
                      }}
                    >
                      {this.state.expressDataPlatform === 1
                        ? '快递鸟'
                        : this.state.expressDataPlatform === 2
                        ? '快递100'
                        : '阿里物流'}
                    </Button>
                  </Tooltip>
                </span>
              </span>
            </Card.Grid>
            <Card.Grid style={{ width: '100%' }}>
              <Timeline>
                {/*获取快递信息*/}
                {this.state.expressData}
              </Timeline>
            </Card.Grid>
          </Card>
        </Drawer>
        <Drawer
          title="商家备注"
          width={420}
          closable
          visible={this.state.drawerSecondShopNote}
          onClose={() => {
            this.setState({
              drawerSecondShopNote: false,
            });
          }}
        >
          {
            <FormItem label="">
              {getFieldDecorator('shopNote', {
                initialValue: model.shopNote || '',
                rules: [],
              })(
                <TextArea
                  type="text"
                  autocomplete="off"
                  autosize={{ minRows: 10 }}
                  style={{ marginBottom: '60px' }}
                  maxLength={200}
                  placeholder="您可以添加或者编辑备注信息"
                />
              )}
            </FormItem>
          }
          <div
            style={{
              position: 'absolute',
              left: 0,
              bottom: 0,
              width: '100%',
              borderTop: '1px solid #e9e9e9',
              padding: '10px 16px',
              background: '#fff',
              textAlign: 'right',
            }}
          >
            <Button
              onClick={() => {
                this.setState({
                  drawerSecondShopNote: false,
                });
              }}
              style={{ marginRight: 8 }}
            >
              <FormattedMessage id="ours.curd.add.cancel" defaultMessage="取消" />
            </Button>
            <Button
              loading={this.state.drawerThridShopNoteLoading}
              onClick={() => {
                //保存商家备注
                this.saveShopNotes(this.getPropsByKey('id'), this.getPropsByKey('shopNote'));
              }}
              type="primary"
            >
              <FormattedMessage id="ours.curd.add.save" defaultMessage="保存" />
            </Button>
          </div>
        </Drawer>
        <Drawer
          title="编辑订单收货人信息"
          width={600}
          closable
          visible={this.state.drawerSecondUserAddress}
          onClose={() => {
            this.setState({
              drawerSecondUserAddress: false,
            });
          }}
        >
          {
            <Form layout="horizontal">
              <Row gutter={{ ...rowGutterPxLayout }}>
                <Col {...colSpanLayoutForUserEdit}>
                  <FormItem label="姓名" {...formItemLayout}>
                    {getFieldDecorator('orderAddress.receiveName', {
                      initialValue: orderAddress.receiveName,
                      rules: [
                        {
                          required: true,
                          message: '姓名必填',
                        },
                        {
                          whitespace: true,
                          message: '不能包含空白符',
                        },
                        {
                          max: 50,
                          message: '最长50个字符',
                        },
                      ],
                    })(
                      <Input
                        type="text"
                        autocomplete="off"
                        {...inputCodeDisabled}
                        maxlength={50}
                        placeholder="姓名"
                      />
                    )}
                  </FormItem>
                </Col>
                <Col {...colSpanLayoutForUserEdit}>
                  <FormItem label="电话" {...formItemLayout}>
                    {getFieldDecorator('orderAddress.receiveTel', {
                      initialValue: orderAddress.receiveTel,
                      rules: [
                        {
                          required: true,
                          message: '电话必填',
                        },
                        {
                          whitespace: true,
                          message: '不能包含空白符',
                        },
                        {
                          max: 11,
                          message: '最长11个字符',
                        },
                        {
                          min: 11,
                          max: 11,
                          message: '手机号必须是11个字符',
                        },
                        rulesReg('mobile'),
                      ],
                    })(
                      <Input
                        type="text"
                        autocomplete="off"
                        {...inputCodeDisabled}
                        maxlength={11}
                        placeholder="电话"
                      />
                    )}
                  </FormItem>
                </Col>
                <Col {...colSpanLayoutForUserEdit}>
                  <FormItem label="所在地区" {...formItemLayout}>
                    {getFieldDecorator('orderAddress.areaOptionCur', {
                      initialValue: orderAddress.areaOptionCur,
                      rules: [
                        {
                          required: true,
                          message: '所在地区必填',
                        },
                      ],
                    })(
                      <Cascader
                        options={areaAlloptions}
                        onChange={value => {
                          //手工设置绑定的值
                          this.props.form.setFieldsValue({ 'orderAddress.areaOptionCur': value });
                        }}
                      />
                    )}
                  </FormItem>
                </Col>
                <Col {...colSpanLayoutForUserEdit}>
                  <FormItem
                    label="详细地址"
                    extra="⚠️订单收货地址请务必在买家知情且同意下修改收货信息"
                    {...formItemLayout}
                  >
                    {getFieldDecorator('orderAddress.receiveAddress', {
                      initialValue: orderAddress.receiveAddress,
                      rules: [
                        {
                          required: true,
                          message: '详细地址必填',
                        },
                        {
                          whitespace: true,
                          message: '不能包含空白符',
                        },
                        {
                          max: 1024,
                          message: '最长1024个字符',
                        },
                      ],
                    })(
                      <TextArea
                        {...inputCodeDisabled}
                        type="text"
                        autocomplete="off"
                        autosize={{ minRows: 5 }}
                        style={{ marginBottom: '30px' }}
                        maxLength={200}
                        placeholder="详细地址"
                      />
                    )}
                  </FormItem>
                </Col>
              </Row>
            </Form>
          }
          <div
            style={{
              position: 'absolute',
              left: 0,
              bottom: 0,
              width: '100%',
              borderTop: '1px solid #e9e9e9',
              padding: '10px 16px',
              background: '#fff',
              textAlign: 'right',
            }}
          >
            <Button
              onClick={() => {
                this.setState({
                  drawerSecondUserAddress: false,
                });
              }}
              style={{ marginRight: 8 }}
            >
              <FormattedMessage id="ours.curd.add.cancel" defaultMessage="取消" />
            </Button>
            <Button
              onClick={() => {
                //保存用户收货地址备注
                this.saveUserAddressInfo();
              }}
              loading={this.state.drawerSecondUserAddressLoading}
              type="primary"
            >
              <FormattedMessage id="ours.curd.add.save" defaultMessage="保存" />
            </Button>
          </div>
        </Drawer>
        <Drawer
          title={this.state.bookSpecialized === true ? '发货(图书专发)' : '商品发货'}
          width={650}
          closable
          destroyOnClose
          visible={this.state.drawerSecondExpressEdit}
          onClose={() => {
            this.setState({
              drawerSecondExpressEdit: false,
            });
          }}
        >
          <Form layout="horizontal" style={{ marginBottom: '150px' }}>
            {!this.state.orderDeliverysHideen && this.state.bookSpecialized === false && (
              <Fragment>
                <Row>
                  <span style={{ display: model.deliveryExpressType !== 'A' ? 'block' : 'none' }}>
                    多期发货：一共{model.orderDeliverys.length}期、待发货
                    {model.orderDeliverys.length -
                      model.orderDeliverys.filter(
                        en =>
                          typeof en.expressDeliveryMethod === 'number'
                      ).length}
                    期
                    <div
                      style={{
                        display:
                          model.deliveryExpressType === 'C' || model.deliveryExpressType === 'D'
                            ? 'block'
                            : 'none',
                      }}
                    >
                      <ETable
                        onSelectRow={uiUtils.onSelectRow.bind(this)}
                        onSelectRowKeys={[
                          'orderDeliverysSelectedIndexs',
                          'orderDeliverysSelectedRows',
                          'orderDeliverysSelectedIds',
                        ]}
                        primaryKey="id"
                        selectedRows={this.state.orderDeliverysSelectedRows}
                        selectedIds={this.state.orderDeliverysSelectedIds}
                        selectedIndexs={this.state.orderDeliverysSelectedIndexs}
                        columns={this.orderDeliverysColumns}
                        dataSource={model.orderDeliverys.filter(
                          en =>
                            typeof en.expressDeliveryMethod !== 'number'
                        )}
                        loading={this.state.infoLoading}
                        pagination={this.state.pagination}
                      />
                    </div>
                  </span>
                </Row>`
              </Fragment>
            )}
            <Row gutter={{ ...rowGutterPxLayout }}>
              <Col {...colSpanLayoutForUserEdit}>
                <FormItem label="发货方式" {...formItemLayout}>
                  {getFieldDecorator('orderAddress.expressDeliveryMethod', {
                    initialValue: orderAddress.expressDeliveryMethod || 0,
                    rules: [
                      {
                        required: true,
                        message: '请选择发货方式',
                      },
                    ],
                  })(
                    <RadioGroup
                      onChange={e => {
                        this.state.model.orderAddress = Object.assign(
                          this.state.model.orderAddress || {},
                          this.props.form.getFieldsValue().orderAddress
                        );
                        this.state.model.orderAddress.expressDeliveryMethod = e.target.value;
                        this.setState({}); //这种写法，是直接修改了this.state的取值，自动检测更新
                      }}
                    >
                      <Radio value={0}>需要物流</Radio>
                      <Radio value={1}>无需物流</Radio>
                    </RadioGroup>
                  )}
                </FormItem>
              </Col>
              <Col {...colSpanLayoutForUserEdit}>
                <FormItem
                  label="快递公司"
                  extra="如🔍到相似的快递公司，请优先选择排列在前面的;&nbsp;搜索支持汉字、拼音、简称等进行搜索"
                  {...formItemLayout}
                >
                  {getFieldDecorator('orderAddress.expressId', {
                    initialValue: orderAddress.expressId || '',
                    rules: [
                      {
                        required: true,
                        message: '请选择快递公司',
                      },
                    ],
                  })(
                    <Select
                      placeholder="支持汉字、拼音、简称等进行搜索"
                      disabled={orderAddress.expressDeliveryMethod === 1}
                      showSearch
                      filterOption={(input, option) =>
                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0 ||
                        `${option.props.namePinyin}`.toLowerCase().indexOf(input.toLowerCase()) >=
                          0 ||
                        `${option.props.expressCode}`.toLowerCase().indexOf(input.toLowerCase()) >=
                          0 ||
                        `${option.props.expressCodeKdniao}`
                          .toLowerCase()
                          .indexOf(input.toLowerCase()) >= 0
                      }
                    >
                      <option value="">请选择快递公司</option>
                      {uiUtils.getOptionList(allExpressInfo)}
                    </Select>
                  )}
                </FormItem>
              </Col>
              <Col {...colSpanLayoutForUserEdit}>
                <FormItem
                  label="快递单号"
                  extra="请仔细填写快速公司和快递单号，发货后15天之内可以修改，过期不可修改"
                  {...formItemLayout}
                >
                  {getFieldDecorator('orderAddress.expressNumber', {
                    initialValue: orderAddress.expressNumber,
                    rules: [
                      {
                        required: true,
                        message: '快递单号必填',
                      },
                      {
                        whitespace: true,
                        message: '不能包含空白符',
                      },
                    ],
                  })(
                    <Input
                      type="text"
                      autocomplete="off"
                      disabled={orderAddress.expressDeliveryMethod === 1}
                      maxlength={100}
                      placeholder="快递单号"
                    />
                  )}
                  <Tooltip
                    placement="top"
                    title="如果没有找到您想要的快递公司，请到快递管理模块进行启用或者新增"
                  >
                    <Link to="/config/express">
                      <Button
                        type="primary"
                        style={{ fontSize: '12px' }}
                        icon="question-circle"
                        size="small"
                      >
                        快递公司管理
                      </Button>
                    </Link>
                  </Tooltip>
                  <Tooltip
                    placement="top"
                    title="多仓发货、多期发货会在所有的商品或者期数发完，系统自动变为已发货；之前系统全显示为待发货"
                  >
                    <Button style={{ marginLeft: '30px' }} icon="question-circle" size="small" />
                  </Tooltip>
                </FormItem>
              </Col>
            </Row>
          </Form>
          <div
            style={{
              position: 'absolute',
              left: 0,
              bottom: 0,
              width: '100%',
              borderTop: '1px solid #e9e9e9',
              padding: '10px 16px',
              background: '#fff',
              textAlign: 'right',
            }}
          >
            <Button
              onClick={() => {
                this.setState({
                  drawerSecondExpressEdit: false,
                });
              }}
              style={{ marginRight: 8 }}
            >
              <FormattedMessage id="ours.curd.add.cancel" defaultMessage="取消" />
            </Button>
            <Button
              onClick={() => {
                //保存物流发货信息
                if (
                  model.deliveryType === 0 &&
                  (model.deliveryExpressType === 'A' ||
                    (model.deliveryExpressType === 'D' && this.state.bookSpecialized === true))
                ) {
                  this.saveExpressInfo();
                } else {
                  this.saveExpressInfoOfMultiple();
                }
              }}
              loading={this.state.drawerSecondExpressEditLoading}
              type="primary"
            >
              <FormattedMessage id="ours.curd.add.save" defaultMessage="保存" />
            </Button>
          </div>
        </Drawer>
        <div style={{ display: 'none' }}>
          {/* eslint-disable-next-line no-return-assign */}
          <Print ref={el => (this.componentRef = el)} printModel={model} />
        </div>
      </Fragment>
    );
  }
}

/* eslint-disable no-class-assign */
//无更多的绑定， 请用 @Form.create() 注解替换
EditForm = Form.create({})(EditForm);
